给一整数无序数组,找到第一个缺失的正整数,时间复杂度为n

//    5.7
//    Given an unsorted integer array, find the first missing positive integer.
//    For example,
//    Given [1,2,0] return 3,
//    and [3,4,-1,1] return 2.
//    Your algorithm should run in O(n) time and uses constant space.
public int firstMissingPositive(int[] nums) {
        int idx = 0;
        while (idx < nums.length) {
            if (nums[idx] == idx + 1 || nums[idx] <= 0 || nums[idx] > nums.length) {
                idx++;
            } else {
                if (nums[idx] == nums[nums[idx] - 1]) {
                    idx++;
                } else {
                    swip(nums, idx, nums[idx] - 1);
                }
            }
        }
        idx = 0;
        while (idx < nums.length && nums[idx] == idx + 1) {
            idx++;
        }
        return idx + 1;
    }
    void swip(int[] ary,int x,int y) {
        int temp = ary[x];
        ary[x] = ary[y];
        ary[y] = temp;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 色不异空阅读 131评论 0 0
  • 巧合,还是天意? 今天有些困有些累,有公司组织的庆祝饭局我也没去,跟我关系聊胜于无,昨天还记录如何搞定老板;对于结...
    秀秀的书阅读 270评论 4 1
  • 昨天,我的直接领导搬家,他要走了,升迁了。中午大伙儿一起吃了个饭。我还记得,上次找他聊时,他说现在我需要学习如何和...
    婷下来思考阅读 157评论 0 0
  • 文/春风柳上归 汉宣帝刘询(刘病已)是中国历史上有名的贤君,在位期间,全国政治清明、社会和谐、经济繁荣...
    春风柳上归阅读 295评论 5 4
  • 买好邮票 铺开信纸 我迅速草写了一封书信 我要找到我阔别了三十多年的老同学 我们曾经一起放学回家 我们曾经一起钻一...
    cloud18阅读 373评论 3 2