zoukankan      html  css  js  c++  java
  • leetcode 41 First Missing Positive ---java

    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.

    这道题求的是在一个乱序数组中缺少的第一个正数,要求时间复杂度o(n)空间复杂度为1。

    先上代码

    package leetcode;
    
    public class firstMissingPositive {
    	public int firstMissingPositive(int[] nums) {
    		int len = nums.length;
    		int i = 0;
    		while( i<len){
    			if( nums[i] == i+1 || nums[i]<0 || nums[i] > len+1)
    				i++;
    			else if( nums[i] != nums[nums[i]-1])
    				swap(nums,i,nums[i]-1);
    			else
    				i++;
    		}
    		i = 0;
    		while(i<len && nums[i] == i+1)
    			i++;
    		return i+1;
        }
    	
    	public void swap(int[] nums, int a,int b){
    		int num = nums[a];
    		nums[a] = nums[b];
    		nums[b] = num;
    	}
    	/*
    	 * 1.求第一个缺少的正数,想通思路很简单。
    	 */
    }
    

     这道题虽然是hard,难点就是在于时间和空间复杂度,但是算法并不困难。

    就是将每一个在1-len之间的正数放在num[i]上,然后遍历一次,遇到的第一个不一样的数就是结果。

  • 相关阅读:
    HSF原理
    Spring IOC 容器源码分析
    Spring Bean注册和加载
    CAP和BASE理论
    Java内存模型
    Java线程模型
    IO复用、多进程和多线程三种并发编程模型
    无锁编程本质论
    An Introduction to Lock-Free Programming
    安装与配置ironic
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5603828.html
Copyright © 2011-2022 走看看