剑指offer面试题40:最小的k个数(快排相关)

这道题,用到了快排思想,就是通过快排中对数组进行分割的partition方法来将数组分割,当该方法返回的index是k-1时,那么他和他前面的数组元素构成的数组,就是前k小的数。

这里面,Partition方法中要注意,j--和i++的顺序,如果先j--,那么循环结束后与最左元素进行交换。如果先i++,与最右元素进行交换

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if(arr == null)
            return null;
        
        int start = 0;
        int end = arr.length - 1;
        int index = -1;
        while(index != k-1){
            if(index > k-1){
                end = index -1;
                index = Partition(arr,start,end);
            }else if(index < k - 1){
                start = index + 1;
                index = Partition(arr,start,end);
            }
        }
        int[] res = new int[k];
        for(int count = 0;count<k;count++){
            res[count] = arr[count];
        }
        return res;

    }

    public int Partition(int[] arr,int start,int end){
        int i = start;
        int j = end;
        int key = start;
        if(arr!=null){
            int mark = arr[start];
            
            while(i<j){
                while(arr[j]>=mark && i<j){
                    j--;
                }
                while(arr[i]<=mark && i<j){
                    i++;
                }
                if(i < j){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
            int temp = arr[start];
            arr[start] = arr[j];
            arr[j] = temp;


        }
        return i;
    }
}

我的快排

	public int Partition(int[] arr,int start,int end) {
		int i = start;
		int j = end;
		int key = arr[start];
		while(i<j) {
			while(arr[j]>=key && i<j) {
				j--;
			}
			while(arr[i]<=key && i<j) {
				i++;
			}
			if(i<j) {
				int temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
		arr[start] = arr[i];
		arr[i] = key;
		return i;
	}
	
	public void quicksort(int[] arr,int start,int end) {
			if(start < end) {
				int index = Partition(arr,start,end);
				quicksort(arr,start,index-1);
				quicksort(arr,index+1,end);
			}
	}

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114402160
今日推荐