Divide and Conquer

来源:互联网 发布:隐藏手机号打电话软件 编辑:程序博客网 时间:2024/06/05 22:54

1. Kth Largest Element in an Array:
当寻找第K大的数时,我们可以用quickselect 方法。
1)The basic idea is to use Quick Select algorithm to partition the array with pivot:

Put numbers < pivot to pivot's leftPut numbers > pivot to pivot's right

2)then:

if indexOfPivot == k, return A[k]else if indexOfPivot < k, keep checking left part to pivotelse if indexOfPivot > k, keep checking right part to pivot

3)Time complexity = O(n)

Discard half each time: n+(n/2)+(n/4)..1 = n + (n-1) = O(2n-1) = O(n), because n/2+n/4+n/8+..1=n-1.

2. 在每行,每列升序排序的数组中查找值。
1). i 定位行,指向每行的第一个元素;j 定位列,开始指向每行的最后一个元素。
2). 遍历每行的最后一个元素定位好行后,用j指针从后往前遍历。

class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if(matrix == null || matrix.length == 0)            return false;        int l = matrix.length;        int r = matrix[0].length;        int i = 0;        int j = r - 1;        while( i < l && j >= 0){            if(matrix[i][j] == target)                return true;            else if(matrix[i][j] < target) i++;            else{                j--;            }        }        return false;    }}
原创粉丝点击