Sword refers to offer 14. Do not modify the array to find repeated numbers (two points)

Topic

Insert picture description here

answer

  1. If additional arrays can be used, we can open a new array to count the number of occurrences of each number.
  1. We can use dichotomy to do this question, because n+1 numbers in 1-n must have two numbers that are repeated, so every time we divide by the middle value, then there must be a number of intervals on the left and right. Is greater than its l-mid+1, this greater than is the repeated number

Code

class Solution {
    
    
public:
    int duplicateInArray(vector<int>& nums) {
    
    
        int l=1,r=nums.size()-1;
        while(l<r){
    
    
            int mid=l+r>>1;
            int s=0;
            for(auto x:nums) {
    
    
                if(x>=l&&x<=mid){
    
    
                    s++;
                }
            }
            if(s>mid-l+ 1) r = mid;
            else l = mid + 1;
        }
        return l;
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114631926