题解 | #缺失的第一个正整数#
缺失的第一个正整数
https://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5
using System; using System.Collections.Generic; using System.Linq; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int minNumberDisappeared (List<int> nums) { // write code here if (nums.Count == 0) return 1; nums.Sort(); for (int i = 0; i < nums.Count; i++) { //移除不是正整数的数 if (nums[i] <= 0) nums.Remove(nums[i]); } List<int> t = new List<int>(nums); Dictionary<int, int> Dic = new Dictionary<int, int>(); for (int i = 0; i < t.Count; i++) { Dic.Add(t[i], i); } List<int> tempList = new List<int>(); foreach (var item in Dic) { tempList.Add(item.Key); } bool flag = false;//是否中断 int index = -1;//中断下标 for (int i = 0; i < tempList.Count - 1; i++) { if (tempList[i + 1] != tempList[i] + 1) { flag = true; index = i; break; } } if (flag) { if (tempList[0] >= 2) { //最小的正整数在最小的左边 return 1; } else { return tempList[index] + 1; } } else { if (tempList[0] >= 2) { //最小的正整数在最小的左边 return 1; } else { return tempList[tempList.Count - 1] + 1; } } } }