LeetCode Missing Number

来源:互联网 发布:wpf编程宝典c 编辑:程序博客网 时间:2024/06/05 09:38

Description:

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Solution:

Just a hint on the bit array.

We can assume:

t1 = a0 ^ a1 ^ a2 ^ ... ^ an

t2 = a0 ^ a1 ^ a2 ^ ... ak ^ ak+1 ^ ... an

ak = t1 ^ t2


<span style="font-size:18px;">import java.util.*;import java.util.Map.Entry;public class Solution {public int missingNumber(int[] nums) {int n = nums.length;int temp = 0;for (int i = 0; i <= n; i++)temp ^= i;for (int i = 0; i < n; i++)temp ^= nums[i];return temp;}}</span>


0 0