leetcode 287. Looking for the number of repetitions (Find the Duplicate Number)

Subject description:

Given an n + 1 contains an integer array nums, which are digital (including 1 and n), found that the presence of at least one repeating integer between 1 to n. Assuming that only a unique integer, find the number of repeats.

Example 1:

输入: [1,3,4,2,2]
输出: 2

Example 2:

输入: [3,1,3,4,2]
输出: 3

Description:

  • You can not change the original array (assuming that the array is read-only).
  • Only use extra space O (1) is.
  • It is less than the time complexity of O (n- 2 ).
  • Only a duplicate array of numbers, but it may be repeated more than once.

solution:

class Solution {
public:
    // method 1: could change the vector
    int findDuplicate1(vector<int>& nums) {
        int n = nums.size()-1;
        int i = n;
        while(i >= 0){
            if(i == nums[i]){
                i--;
            }else{
                if(nums[i] == nums[nums[i]]){
                    return nums[i];
                }else{
                    swap(nums[i], nums[nums[i]]);
                }
            }
        }
        return -1;
    }
    
    // method 2: not change the vector
    int findDuplicate2(vector<int>& nums) {
        int n = nums.size()-1;
        int fast = 0, slow = 0;
        do{
            fast = nums[fast];
            fast = nums[fast];
            slow = nums[slow];
        }while(nums[fast] != nums[slow]);
        fast = 0;
        while(nums[fast] != nums[slow]){
            fast = nums[fast];
            slow = nums[slow];
        }
        return nums[fast];
    }
    
    int findDuplicate(vector<int>& nums) {
        return findDuplicate2(nums);
    }
};

Guess you like

Origin www.cnblogs.com/zhanzq/p/10932259.html