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?

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


题意:在数组中有0-n的整数,但是缺少一个,求缺少的

分类:数组


解法1:我能想到最直观的思路就是等差数列求和,总数=(1+n)*n/2

所以我们求出全齐情况下的和,然后将数组中的所有数都减去

那么剩下的就是缺少的那个数了

[java]  view plain  copy
  1. public class Solution {  
  2.     public int missingNumber(int[] nums) {  
  3.         int len = nums.length;  
  4.         int sum = (1+len)*len/2;  
  5.         for(int i=0;i<len;i++){  
  6.             sum -= nums[i];  
  7.         }  
  8.         return sum;  
  9.     }  
  10. }  

解法2:使用异或。因为数组中缺少一个,如果这个数组,和全的数组异或,那么异或得到的结果就是缺少的数。

两个相同的数异或会变成0。而缺少的数,没有和它相同的,所以就只剩下它了。

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

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/48138477

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值