Leetcode topic 287. Looking for the number of repetitions (medium)

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: 

Input: [1,3,4,2,2] 
Output: 2 
Example 2: 

Input: [3,1,3,4,2] 
Output: 3 
Description: 

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

Analysis of ideas:

The key: the key to solving the problem is to locate the "number" do two points, rather than the index of the array do half. To locate the "number" according to the meaning of problems between 1 and n, each half of the search range can be reduced by half.

In [1, 2, 2, 3, 4, 5, 6, 7], for example, a total number of 8, each number between 1 and 7. 1 and 7 bits is 4, traverse the entire array, count the number of integers less than 4, should be at most three, more than three it means that if the number of repeats present in the interval [1,4) (Note: Left right open and closed); otherwise, the number of repeats present in the interval [4,7] (Note: all around closed) in. Here integer less than 4, there are four (which are 1, 2, 2, 3), and therefore the right half cut section, even in the median is also cut. And so on, and finally the interval smaller and smaller until it becomes an integer that is the number we're looking for duplicate.

Code:

class Solution {
    public static int findDuplicate(int[] nums) {

        int len = nums.length;
        int left = 1;
        int right = len - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            int count = 0;
            for (int i = 0; i < len; i++) {
                if (nums[i] <=mid) {
                    count++;
                }
            }
            if (count > mid) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}

Time complexity: O (nlogn)

Space complexity: O (1)

 

Guess you like

Origin www.cnblogs.com/ysw-go/p/11926465.html