0608-2020-LEETCODE-192.周赛回顾-(自定义数组排序算法/浏览器访问记录)

这个就直接自定义排序方法就行。其中自定义排序方法:可以简洁地写成:

Arrays.sort(temp,(x,y) ->
    (Math.abs(x - m) == Math.abs(y - m) ? y - x : Math.abs(y - m) - Math.abs(x - m)));
class Solution {
    public int[] getStrongest(int[] arr, int k) {
        Arrays.sort(arr);
        int[] res = new int[k];
        int len = arr.length;
        int m = arr[(len - 1) / 2];
        Integer[] temp = new Integer[arr.length];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = arr[i];
        }
        Arrays.sort(temp, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                int x = Math.abs(o1 - m);
                int y = Math.abs(o2 - m);
                if (x != y){
                    return - Integer.compare(x,y);
                } else {
                    return - Integer.compare(o1, o2);
                }

            }
        });
        for (int i = 0; i < k; i++) {
            res[i] = temp[i];
        }
        return res;
    }
}

浏览器的访问记录:
其实自己写出来了,只是有一个小bug,当stack1没有可以back的值时应该返回当前访问的界面,但是由于自己当时有别的更重要的事情要忙,所以没办法只能提交两题,自己两题用了20多分钟,还可以,但是需要继续努力。

class BrowserHistory {

    Deque<String> stack1 = new ArrayDeque<String>();
    Deque<String> stack2 = new ArrayDeque<String>();

    public BrowserHistory(String homepage) {
        stack1.push(homepage);
    }

    public void visit(String url) {
        while (!stack2.isEmpty()){
            stack2.pollFirst();
        }
        stack1.addLast(url);
    }

    public String back(int steps) {
        String res = "";
        while (stack1.size() > 1 && steps > 0){
            stack2.addFirst(stack1.pollLast());
            res = stack1.peekLast();
            steps--;
        }
        if ("".equals(res)){
            return stack1.peekLast();
        }
        return res;

    }

    public String forward(int steps) {
        String res = "";
        while (!stack2.isEmpty() && steps > 0){
            res = stack2.pollFirst();
            stack1.addLast(res);
            steps--;
        }
        if (("").equals(res)){
            return stack1.peekLast();
        }
        return res;
    }

    public static void main(String[] args) {
        BrowserHistory browserHistory = new BrowserHistory("zav.com");
        browserHistory.visit("kni.com");
        System.out.println(browserHistory.back(7));
        System.out.println(browserHistory.back(7));
        System.out.println(browserHistory.forward(5));
        System.out.println(browserHistory.forward(1));
        browserHistory.visit("pwrrbnw.com");
        browserHistory.visit("mosohif.com");
        System.out.println(browserHistory.back(9)); }
}

你可能感兴趣的:(LEETCODE,数据结构)