LeetCode 8

  • ArraySort

  java.util.Arrays.sort(T[] a, Comparator<? super T> c) method sorts the specified array of objects according to the order induced by the specified comparator.

  a-- this is the array to be sorted

  c-- the comparator to determine the order of the array, a null value indicates that the elements' natural ordering should be used.

    • new Comparator<int[]>(){ //返回一个泛型为int[]的comparator

         public int compare(int[] p1, int[] p2){

          从小到大,前-后

          从大到小,后-前

        }

      }

    • Java 8: Arrays.sort(people, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]);
    • Arrays.sort(people, Comparator.comparing( (int[] arr) -> arr[0]).reversed() );

      reversed() : returns a comparator that impose  the reverse ordering  of the comparator

      comparing(): accepts a function that extract a comparable sort key, returns a comparator that compares by the sort key. 注:(int[] arr) -> arr[0]) 就是comparing的input function


 

406. Queue Reconstruction by height

public class Solution {
    public int[][] reconstructQueue(int[][] people) {
        //pick up the tallest guy first
        //when insert the next tall guy, just need to insert him into kth position
        //repeat until all people are inserted into list
        Arrays.sort(people,new Comparator<int[]>(){
           @Override
           public int compare(int[] p1, int[] p2){
                return p1[0] == p2[0] ?  p1[1] - p2[1] : p2[0] - p1[0];
            }
        });
        List<int[]> res = new LinkedList<>();
        for(int[] cur : people){
            res.add(cur[1],cur);       
        }
        return res.toArray(new int[people.length][]);
    }
}

--------------------------------------------------------------------------------------------
Arrays.sort(people, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]);
        List<int[]> ans = new LinkedList<>();
        for (int[] p : people) {
            ans.add(p[1], p);
        }
        return ans.toArray(new int[0][0]);
  •  Binary Search

33. Search in Rotated Sorted Array

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0) return -1;
        int low = 0;
        int high = nums.length - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] == target) {return mid;}
            else if(nums[low] <= nums[mid]){
                if(target < nums[mid] && target >= nums[low]){
                    high = mid - 1;
                }else low = mid + 1;
            }else{
                if(target > nums[mid] && target <= nums[high]){
                    low = mid + 1;
                }else high = mid - 1;
            }
        }
        return -1;
    }
}

主要是注意判断一下情况,mid位于被rotate的部分还是属于非rotate的部分。


 

posted @ 2017-12-08 01:07  nina阿瑶  阅读(234)  评论(0编辑  收藏  举报