• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Missing Number

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.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Best Solution: Bit manipulation

The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.

 1 class Solution {
 2     public int missingNumber(int[] nums) { //xor
 3         int res = nums.length;
 4         for(int i=0; i<nums.length; i++){
 5             res ^= i;
 6             res ^= nums[i];
 7         }
 8         return res;
 9     }
10 }

 

Summation approach:

1 public int missingNumber(int[] nums) { //sum
2     int len = nums.length;
3     int sum = (0+len)*(len+1)/2;
4     for(int i=0; i<len; i++)
5         sum-=nums[i];
6     return sum;
7 }

 

 

 

因为输入数组是0,1,2,...,n。 把nums[i]放到i的位置上.  nums[i] != i的即为missing number.

注意6-9行不可先令 temp = nums[i]

 1 public class Solution {
 2     public int missingNumber(int[] nums) {
 3         int res = nums.length;
 4         for (int i=0; i<nums.length; i++) {
 5             if (nums[i] < nums.length && nums[nums[i]] != nums[i]) {
 6                 int temp = nums[nums[i]];
 7                 nums[nums[i]] = nums[i];
 8                 nums[i] = temp;
 9                 i--;
10             }
11         }
12         for (int i=0; i<nums.length; i++) {
13             if (nums[i] != i) res = i;
14         }
15         return res;
16     }
17 }

 

posted @ 2015-12-24 08:50  neverlandly  阅读(279)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3