Find the same array

Title 03 interview questions: find duplicate numbers array

All numbers in an array of length nums n's are in the range of 0 ~ n-1. Some digital array is duplicated, but do not know how many numbers repeat, do not know each number was repeated several times. Please find an array of any one of the duplicate numbers.

// general idea: first array from small to large, if there is no repetition of elements, each element and its index should be the same, but you can sort the search is complete when convenient
/ *
Specifically: in the array each element is traversed if there is an element where the index is not equal, then
if there is an element with the index of this element is the same element as the element is repeated
if there is an element with the subscript the value of this element are not identical, the two exchange

For example:
Enter
[2, 3, 1, 0, 2, 5, 3]
Output: 2 or 3


``
public class Solution {
    public int findRepeatNumber(int[] nums) 
    {
    	int t=0;
        for(int i=0;i<nums.length;i++)
        {
            if(i!=nums[i])
            {
                if(nums[i]==nums[nums[i]])
                    // System.out.print(nums[i]+"  ");
                    return nums[i];
                else 
                {
                    t=nums[i];
                    nums[i]=nums[nums[i]];
                    nums[t]=t;
                }
            }
        }
        return 0;
    }
    public static void main(String[] args)
    {
        Solution ss=new Solution();
        int[] nums={2, 3, 1, 0, 2, 5, 3};
        ss.findRepeatNumber(nums);
    }
}

The time complexity is O (n)

  • When execution: 1 ms, beat the 94.14% of all users to submit in Java
    memory consumption: 58.6 MB, defeated 100.00% of users in all Java submission
Published 16 original articles · won praise 1 · views 1263

Guess you like

Origin blog.csdn.net/cf1169983240/article/details/104319189