leetcode--Missing Number

来源:互联网 发布:php查找字符串位置 编辑:程序博客网 时间:2024/06/07 11:13

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.csdn.net/crazy__chen/article/details/48138477

原创粉丝点击