java 670.最大Swap.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 670.最大Swap.java相关的知识,希望对你有一定的参考价值。

class Solution {
    private class Node {
        int val;
        int idx;
        public Node(int val, int idx) {
            this.val = val;
            this.idx = idx;
        }
    }
    private int arrToNum(LinkedList<Integer> numArr) {
        int res = 0;
        for (int i = 0; i < numArr.size(); i++) {
            res = res * 10 + numArr.get(i);
        }
        return res;
    }
    public int maximumSwap(int num) {
        PriorityQueue<Node> maxHeap = new PriorityQueue<>(new Comparator<Node>(){
            public int compare(Node a, Node b) {
                if (a.val == b.val) {
                    return b.idx - a.idx;
                }
                return b.val - a.val;
            }
        });
        LinkedList<Integer> numArr = new LinkedList<>();
        while (num != 0) {
            numArr.addFirst(num % 10);
            num /= 10;
        }
        for (int i = 0; i < numArr.size(); i++) {
            maxHeap.offer(new Node(numArr.get(i), i));
        }
        for (int i = 0; i < numArr.size(); i++) {
            Node cur = maxHeap.poll();
            if (numArr.get(i) == cur.val && i != cur.idx) {
                List<Node> backup = new ArrayList<>();
                while (!maxHeap.isEmpty() && maxHeap.peek().val == cur.val) {
                    backup.add(maxHeap.poll());
                }
                maxHeap.offer(cur);
                for (Node n : backup) {
                    if (n.idx != i) {
                        maxHeap.offer(n);
                    }
                }
            } else if (numArr.get(i) != cur.val) {
                int temp = numArr.get(i);
                //numArr.get(i) = numArr.get(cur.idx);
                //numArr.get(cur.idx) = temp;
                numArr.set(i, numArr.get(cur.idx));
                numArr.set(cur.idx, temp);
                return arrToNum(numArr);
            }
        }
        return arrToNum(numArr);
    }
}

/*
2736
9973
1357
1993
*/

以上是关于java 670.最大Swap.java的主要内容,如果未能解决你的问题,请参考以下文章

每日一题670. 最大交换

数组670. 最大交换

670. 最大交换-贪心

LeetCode 670 最大交换[暴力 贪心] HERODING的LeetCode之路

670. Maximum Swap

Day670.Servlet规范&Servlet容器 -深入拆解 Tomcat & Jetty