题解 | #缺失的第一个正整数#

缺失的第一个正整数

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;
            }
        }
    }
}

全部评论

相关推荐

09-17 20:37
已编辑
长沙学院 Java
涂莱:学院本重心后移,金10银11,甚至金11银12,战线拉长一点,对于学院本来说秋招是个持久战,加油吧
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务