zoukankan      html  css  js  c++  java
  • LeetCode 41 First Missing Positive(找到数组中第一个丢失的正数)

     
    给出一个未排序的数组,求出第一个丢失的正数。
    给出组合为int []nums = {0,1,3,-1,2,5};
    下面为按照参考代码1执行交换运算的输出结果
     
    0 1 3 -1 2 5
    1 0 3 -1 2 5
    1 0 3 -1 2 5
    1 0 3 -1 2 5
    1 0 3 -1 2 5
    1 2 3 -1 0 5
    1 2 3 -1 0 5
    1 2 3 -1 5 0
    1 2 3 -1 5 0
    4
     
    参考代码1: 
    public class Solution41 {
        public int firstMissingPositive(int[] A) {
        // added line9 condition to avoid infinite loop
        // added line13, the i--, to check the swapped item. Or we failed to check all the numbers.
        // ref http://stackoverflow.com/questions/1586858/find-the-smallest-integer-not-in-a-list
                if (A.length == 0) return 1;//长度等于0 直接返回1
                for (int i = 0; i < A.length; i++) {//遍历
                            //是整数,小于数组长度,不等于当前下标
                    if (A[i] <= A.length && A[i] > 0 && A[i] != i+1) {
                        if (A[A[i]-1] != A[i]) { //line 9 进行交换操作
                            int tmp = A[A[i]-1];
                            A[A[i]-1] = A[i];
                            A[i] = tmp;
                            i--; //line 13
                        }
                    }            
                }
                for (int i = 0; i < A.length; i++) {
                    if (A[i] != i+1) return i+1;
                }
                return A.length+1;
        }
    }

    参考代码2:

    package leetcode_50;
    
    
    /***
     * 
     * @author pengfei_zheng
     * 找到第一个丢失的正数
     */
    public class Solution41 {
        public static int firstMissingPositive(int[] nums) {
            int i = 0;
            while(i < nums.length){
                if(nums[i] == i+1 || nums[i] <= 0 || nums[i] > nums.length) i++;
                else if(nums[nums[i]-1] != nums[i]) swap(nums, i, nums[i]-1);
                else i++;
            }
            i = 0;
            while(i < nums.length && nums[i] == i+1) i++;
            return i+1;
        }
    
        private static void swap(int[] A, int i, int j){
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
        public static void main(String[]args){
            int []nums = {1,1};
            System.out.println(firstMissingPositive(nums));
        }
    }
     
     
  • 相关阅读:
    Spring-web初始化流程简图
    记一次升级Tomcat
    Spring-Task思维导图
    2019的第一个工作日
    RocketMQ专题2:三种常用生产消费方式(顺序、广播、定时)以及顺序消费源码探究
    RocketMQ专题1:入门
    博客搬家到云栖社区
    ActiveMQ专题2: 持久化
    ActiveMQ专题1: 入门实例
    linux下怎么卸载自带的JDK和安装想要的JDK
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/6537774.html
Copyright © 2011-2022 走看看