Title description:

Find duplicate numbers in the array. All numbers in an array of length N, nums, are in the range 0 to n-1. Some numbers in the array are repeated, but we don't know how many are repeated, or how many times each number is repeated. Please find any duplicate number in the array. Example 1: Input: [2, 3, 1, 0, 2, 5, 3] Output: 2 or 3Copy the code

Code:

class Solution {
    public int findRepeatNumber(int[] nums) {
        // Use the set set to find duplicate numbers
        Set<Integer> set = new HashSet<>();
        int repeat = -1;
        for(int num: nums){
          if(! set.add(num)){ repeat = num;break; }}returnrepeat; }}Copy the code

code

class Solution {
    public int findRepeatNumber(int[] nums) {
      	// Sort first
        Arrays.sort(nums);
        int repeat = 0;
      	// Find repeating elements in place
	if(nums[0] != nums[1]) repeat = nums[0];
	for(int i=1; i<nums.length-1; i++){if(nums[i]==nums[i-1] || nums[i]==nums[i+1]){ repeat = nums[i]; }}if(nums[nums.length-1] == nums[nums.length-2]) {
	    repeat=nums[nums.length-1];
        }
        returnrepeat; }}Copy the code