Leetcode287. Looking for the number of repetitions

topic

  • 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
  • Note:
    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 (n2).
    Only a duplicate array of numbers, but it may be repeated more than once.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-the-duplicate-number
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

method

class Solution {
    public int findDuplicate(int[] nums) {
        Set<Integer> set= new HashSet<Integer>();
        for (int num : nums) {
            //如果已经存在则重复了
            if (set.contains(num)) {
                return num;
            }
            set.add(num);
        }

        return -1;
    }
}

Thinking

- using a set of judgment reciprocity

Next summary

  • There is no better way to achieve the requirements described in the title?
Published 28 original articles · won praise 0 · Views 178

Guess you like

Origin blog.csdn.net/qq_22017379/article/details/103937070