A concise code of c++ in both iteration and recursion


  • 0
    D
    int findMin(vector<int>& arr, int s, int e){
            assert(s<e);
            if(s==e-1) return arr[s];
            int m = s+(e-s)/2;
            if(arr[m]>arr[s])
                return min(arr[s], m+1<e?findMin(arr, m+1, e):arr[s]);
            else if(arr[m]<arr[s])
                return min(arr[m], s<m?findMin(arr, s, m):arr[m]);
            else
                return min(s<m?findMin(arr, s, m):arr[s], m+1<e?findMin(arr, m+1, e):arr[m]);
        }
    
    int findMin(vector<int> &num) {
            //return findMin(num, 0, num.size());
            int s = 0;
            int e = num.size();
            assert(s<e);
            int m = num[0];
            while(s<e){
                int mid = s+(e-s)/2;
                if(num[mid]>num[s]){
                    m = min(m, num[s]);
                    if(mid+1>=e) return m;
                    s = mid+1;
                }
                else if(num[mid]<num[s]){
                    m = min(m, num[mid]);
                    if(s>=mid) return m;
                    e = mid;
                }
                else{
                    if(mid==s) 
                        return min(m, num[s]);
                    else
                        s++;
                }
            }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.