java 41. First Missing Positive(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 41. First Missing Positive(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int firstMissingPositive(int[] nums) {

        for(int i=0;i<nums.length;i++){
        	while(nums[i]!=i+1){
                int sindex = nums[i]-1;
        		if(sindex<0||sindex>=nums.length)
        			break;
        		if(nums[i]==nums[sindex])
        			break;
        		int tmp = nums[i];
        		nums[i] = nums[sindex];
        		nums[sindex] = tmp;
        	}
        }
        for(int i=0;i<nums.length;i++){
        	if(nums[i]!=i+1)
        		return i+1;
        }
        return nums.length+1;
    }
}
public class Solution {
    private void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
    public int firstMissingPositive(int[] nums) {
        //if (nums == null || nums.length < 1) return 1;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            //while (nums[i] > 0 && nums[i] <= len && nums[i] != i + 1) {
            while (nums[i] > 0 && nums[i] <= len && nums[nums[i] - 1] != nums[i]) { // []
                swap(nums, i, nums[i] - 1);
            }
        }
        for (int i = 0; i < len; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        return len + 1;
        
    }
}

以上是关于java 41. First Missing Positive(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 41. First Missing Positive(#)。java

java 41. First Missing Positive(#)。java

java 41. First Missing Positive(#)。java

leetcode:41. First Missing Positive (Java)

leetcode:41. First Missing Positive (Java)

leetcode:41. First Missing Positive (Java)