268. Missing Number
2016-07-07 22:12
295 查看
iven 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?由于题干说明去取的数是从0一直到n,所以例如13,14,15……20这样的序列是不会出现的。先把两个边界处理一下,缺0的情况和完整的情况,缺0的话就是n项和了,完整的话就是n-1项和。再处理一般情况,一般情况直接用min加到max应该的和减去前面的sum就是所求。
public int missingNumber(int[] nums) { int len=nums.length; if(len<1) return 0; long min=Integer.MAX_VALUE; long max=Integer.MIN_VALUE; long sum=0; for(int i=0;i<len;i++) { min=Math.min(nums[i], min); max=Math.max(nums[i],max); sum+=nums[i]; } if(sum==(len*(len+1)/2)) return 0; if(sum==(len*(len-1)/2)) return (int) (max+1); return (int) ((min+max)*(len+1)/2-sum); }简洁版 https://discuss.leetcode.com/topic/24535/4-line-simple-java-bit-manipulate-solution-with-explaination/3 since the n numbersare from
[0, n],we can just add all the numbers from
[0, n]togetherand minus the sum of the n-1 numbersin array.
public static int missingNumber(int[] nums) { int sum = nums.length; for (int i = 0; i < nums.length; i++) sum += i - nums[i]; return sum; }-----------------------------------------------------------------------------------位操作版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 missingnumber.
public int missingNumber(int[] nums) { int xor = 0, i = 0; for (i = 0; i < nums.length; i++) { xor = xor ^ i ^ nums[i]; } return xor ^ i; }
---------------------------------------------------------
交换元素,把相应的数放在相应的index上,使得num[i]=i+1,然后从头到尾第一个不满足4000这个关系的数就是缺失的数,全部都满足的话,缺失的是0.
public class Solution {public static int missingNumber(int[] nums){int len=nums.length;if(len==0)return 0;for(int i=0;i<len;i++){while(nums[i]!=0&&nums[i]!=i+1){int temp=nums[nums[i]-1];nums[nums[i]-1]=nums[i];nums[i]=temp;}}int missing=-1;for(int i=0;i<len;i++)if(nums[i]!=i+1){missing=i;break;}return missing+1;}}
相关文章推荐
- Loadrunner关于页面检查的几个函数详解
- Linux常用而且好玩的命令
- Html学习笔记2
- 进程间通信的方法
- JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
- 2016/07/07 apmserv5.2.6 Apache启动失败,请检查相关配置。MySQL5.1已启动。
- HBase学习之三: hbase filter(过滤器)和coprocessor(协处理器)统计行数的简单应用
- android笔记:BroadcastReceiver
- 初学hibernate
- 剑指offer-4-面试题22:栈的压入、弹出序列
- [置顶] 【Linux】 进程通信--消息队列
- centos安装rabbitmq消息队列
- 2016/07/07 wamp中apache2.4.9允许外部访问的配置 重点是版本 版本不同配置效果不同
- NHibernate系列文章十六:使用程序集管理NHibernate项目(附程序下载)
- extern 声明 vs2012
- maven lib 复制到工程中
- win7环境mysql安装
- 最长回文串
- linux 内核配置与编译
- leetcode: Binary Tree Preorder Traversal