① Given a, ..., n, n sequence number 0, 1, 2 comprise, find the number 0 .. n does not appear in the sequence. ② all numbers in an array of length n's are in the range of 0 to n-1, find a duplicate array of any number

Somewhat similar to the two problems:
First, a given containing 0, 1, 2, ..., n, the sequence number n, to find the 0 ... n does not appear in that number in the sequence.
Input: [3,0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Method a: Gauss formula: 1 + 2 + 3 + ... + n = (1 + n) * n / 2

	public static int Solution(int[] arr) {
		int len = arr.length;
		int res = (len*(len+1))/2;
		for (int i = 0; i < arr.length; i++) {
			res -= arr[i];
		}
		return res;
	}

Method two: Bitwise

public static int Solution(int[] arr) {
		int res = 0;
		for (int i = 0; i < arr.length; i++) {
			res ^= arr[i]^i;
			
		}
		System.out.println("res="+res+",arr.length="+arr.length);
		
		return res^arr.length;
	}

The main function:

public static void main(String[] args) {
		int[] arr = {8,6,9,2,3,5,7,0,1};
		int res = Solution(arr);
		System.out.println(res);
	}

Second, all numbers in an array of length n's are in the range 0 to n-1, find a duplicate array of any number.

  • Ideas:
  • For solving this array element [0, n-1] the problem range, the element can be adjusted to a value i of i-th position.
    In (2, 3, 1, 0, 2, 5), for example, to traverse the 4 position, this position is the number 2, but has a value of 2 in the second position, it is possible to know repeated 2 .

** time complexity is O (n), the spatial complexity is O (1).

public static int Solution(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			while(arr[i] != i) {
				if(arr[i] == arr[arr[i]]) {
					return arr[i];
				}
				swap(arr,arr[i],i);
			}
		}
		return -1;
	}
	private static void swap(int[] arr, int m, int n) {
		int temp = arr[m];
		arr[m] = arr[n];
		arr[n] = temp;
		
	}
	public static void main(String[] args) {
		int[] arr = {2, 3, 1, 0, 2 ,5};
		int res = Solution(arr);
		System.out.println(res);
	}
	
Published 114 original articles · won praise 16 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44026997/article/details/104966503