【數組】A080_LC_缺失的第一個正數(索引對比值)

一、Problem

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:
Input: [1,2,0]
Output: 3

Example 2:
Input: [3,4,-1,1]
Output: 2

Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:

Your algorithm should run in O(n) time and uses constant extra space.


二、Solution

方法一:對比

O(1) 空間實在沒有想出來…

但正確思路是:我們知道索引從 0 開始,最小整數是 1,所以 1 應該出現是 a[0],以此類推

class Solution {
    public int firstMissingPositive(int[] a) {
    	int n = a.length;
    	for (int i = 0; i < n; ) {
    		int v = a[i];
    		if (v > 0 && v <= n && a[v-1] != a[i]) {
    			int t = a[i];
    			a[i] = a[v-1];
    			a[v-1] = t;
    		} else {
                i++;
            }
    	}
    	for (int i = 0; i < n; i++) if (i+1 != a[i]) {
    		return i+1;
        }
        return n+1;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章