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 Python3] 41. First Missing Positive 一步步優化LeetCodePython優化
- 【Leetcode】163. Missing RangesLeetCode
- [LeetCode] 2028. Find Missing ObservationsLeetCode
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- Number.POSITIVE_INFINITY
- LeetCode 41. 缺失的第一個正數LeetCode
- 14-1 雜湊表基礎 / Leetcode first uniq charLeetCode
- leetcode【210】【Depth-first Search】Course Schedule II【c++版本】LeetCodeC++
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- Pandas fillna('Missing')
- Missing Subsequence Sum
- leetcode:41. 缺失的第一個正數(困難,陣列)LeetCode陣列
- Comodo Positive SSL證書簡要介紹
- missing ) after argument list
- find: missing argument to `-exec'
- Missing MSI and MSP files
- your Android sdk is missingAndroid
- First Blog
- 7.93 FIRST
- :first-child與:first-of-type 區別
- gerrit "missing Change-Id"
- OPatch install "Missing command :fuser"
- B. Missing Subsequence Sum
- My first blog!
- my first demo
- First steps with Incus
- My First Blog
- 詳解Comodo Positive SSL證書及其適用物件物件
- GAMES001&mit missing semesterGAMMIT
- shell指令碼報錯:[: missing `]‘指令碼
- vue41Vue
- Andy's First Dictionary
- 【EF Core】Code first
- 7.94 FIRST_VALUE
- Head First Python (一)Python
- Positive Luxury:奢侈品可持續立法的未來UX
- Dynamic Web Project option missing in Eclipse KeplerWebProjectEclipse