public class Solution { public int MissingNumber(int[] nums) { var list = nums.OrderBy(x => x).ToList(); var preNum = 0; foreach (var l in list) { if (l != preNum) { return preNum; } preNum++; } return preNum; } }
https://leetcode.com/problems/missing-number/#/description
补充一个python的实现:
1 class Solution: 2 def missingNumber(self, nums): 3 missing = len(nums) 4 for i, num in enumerate(nums): 5 missing ^= i ^ num 6 return missing
不使用位运算特性:
1 class Solution: 2 def missingNumber(self, nums: List[int]) -> int: 3 nums.sort() 4 prenum = 0 5 for x in nums: 6 if x != prenum: 7 return prenum 8 else: 9 prenum += 1 10 return prenum