Leetcode 41 First Missing Positive
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.
這個題是查詢第一個最小的正整數。
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) // 防止越界
return 1;
for (int i = 0; i < nums.length; i++) {
// nums[i] - 1 < nums.length 超出範圍不交換 nums[i] != nums[nums[i] - 1] 相等不交換
while (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i] - 1]) {
swap(nums, i, nums[i] - 1);
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1; // 第一個不相等就返回
}
}
return nums[nums.length - 1] + 1; // 陣列交換後是有序正數,就返回最大 + 1
}
public void swap(int[] nums, int i, int j) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
}
相關文章
- Leetcode First Missing PositiveLeetCode
- LeetCode:Missing Number And First Missing PositiveLeetCode
- Leetcode-First Missing PositiveLeetCode
- First Missing Positive leetcode javaLeetCodeJava
- First Missing Positive【hard】
- [LeetCode Python3] 41. First Missing Positive 一步步優化LeetCodePython優化
- 41. First Missing Positive(找到陣列中未出現的最小正整數)陣列
- Leetcode-Missing RangesLeetCode
- 【Leetcode】163. Missing RangesLeetCode
- [LeetCode] 2028. Find Missing ObservationsLeetCode
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Number.POSITIVE_INFINITY
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- SAP Fiori Positive User Experience
- LeetCode 41. 缺失的第一個正數LeetCode
- 14-1 雜湊表基礎 / Leetcode first uniq charLeetCode
- leetcode【210】【Depth-first Search】Course Schedule II【c++版本】LeetCodeC++
- OCP(11g)-----> oracle First In First Out (FIFO)/Last In First OutOracleAST
- leetcode:41. 缺失的第一個正數(困難,陣列)LeetCode陣列
- Missing Subsequence Sum
- ntldr is missing怎麼解決? ntldr is missing怎麼回事?
- jQuery first()jQuery
- jQuery :firstjQuery
- vue41Vue
- :first-child與:first-of-type 區別
- Comodo Positive SSL證書簡要介紹
- HDU5183Negative and Positive (NP)(雜湊表)
- LintCode-Interleaving Positive and Negative Numbers.
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- Entity Framework Code-First(2):What is Code-First?Framework
- Entity Framework Code-First(4):Simple Code First ExampleFramework
- Entity Framework Code-First(5):Code First ConventionsFramework
- first oracle sqlOracleSQL
- gerrit "missing Change-Id"
- your Android sdk is missingAndroid
- NILDR is Missing解決方案
- B. Missing Subsequence Sum
- 41. The Security Namespacenamespace