LeetCode-探索-初级算法-其他-6. 缺失数字(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 缺失数字
-
语言:java
-
思路:先排序,再找出缺失的数字
-
代码(11ms,23.83%丢人):
class Solution { public int missingNumber(int[] nums) { Arrays.sort(nums); for(int i = 0; i < nums.length ; ++i){ if(nums[i]!=i) return i; } return nums.length; } }
-
参考代码(0ms):利用求0-n的和来判断缺失的数字
class Solution { public int missingNumber(int[] nums) { int sum=(nums.length+1)*nums.length/2; for(int i=0;i<nums.length;i++){ sum-=nums[i]; } return sum; } }
-
参考后重写(1ms):
class Solution { public int missingNumber(int[] nums) { int sum = nums.length * (nums.length + 1) / 2; for(int i = 0; i < nums.length; ++i){ sum-=nums[i]; } return sum; } }