The minimum number "wins the offer" is inscribed rotating array of Java version 8

(Ascending find the minimum number of rotating array)

The book Methods: This topic is to look for the characteristics of the array, and then to write according to this feature. Increment array rotated into two sections increasing sequence, we find the midpoint, if larger than the first element, he said in the first paragraph increasing sequence, if smaller than the first element in the sequence represents the increment in the second paragraph . This can be done with recursion or iteration. One thing to note is that if intermediate element and the first elements are equal, and and last elements are equal, this time we can not see how this element is in ascending sequence in the first or in the second increase in sequence, this time to start to finish scanning to determine the minimum element. Another point to note is the array may not be rotated, that is put in front 0 array elements moved back, this time we should not enter or recursive loop.

    public int find(int[] a){
        int index1 = 0;
        int index2 = a.length-1;
        int mid = index1;
        
        while(a[index1] >= a[index2]){
            //index1始终在第一个序列,index2始终在第二个序列,当发生下面的情况时,找到最小值。
            if(index1 == index2-1){
                mid = index2;
                break;
            }
            
            mid = index1 + (index2-index1)/2;
            
            //如果发生了这种情况,不能通过迭代继续寻找下去了
            if(a[mid] == a[index1] && a[mid] == a[index2]){
                return searchMin(a, index1, index2);
            }
            
            
            if(a[mid] >= a[index1]){
                index1 = mid;
            }else if(a[mid] <= a[index2]){
                index2 = mid;
            }
        }
        return a[mid];
    }
    private int searchMin(int[] a, int start, int end){
        int result = a[start];
        for(int i=start+1; i<=end; i++){
            if(a[i] < result){
                result = a[i];
            }
        }
        return result;
    }

Guess you like

Origin www.cnblogs.com/czjk/p/11611209.html