A prefix nums[0..i] is sequential if, for all 1 <= j <= i, nums[j] = nums[j - 1] + 1. In particular, the prefix consisting only of nums[0] is
sequential.
Return thesmallest integerxmissing fromnumssuch thatxis greater than or equal to the sum of thelongest sequential prefix.
Input: nums =[1,2,3,2,5]Output: 6Explanation: The longest sequential prefix of nums is[1,2,3]with a sum of 6.6is not in the array, therefore 6is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
Input: nums =[3,4,5,1,12,14,13]Output: 15Explanation: The longest sequential prefix of nums is[3,4,5]with a sum of 12.12,13, and 14 belong to the array while15 does not. Therefore 15is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
First, find the longest sequential prefix and compute its sum. Then, find the smallest integer greater than or equal to this sum that is missing from the array. A set allows for fast lookup of missing numbers.
#include<vector>#include<unordered_set>usingnamespace std;
classSolution {
public:int missingInteger(vector<int>& nums) {
int n = nums.size(), i =1, s = nums[0];
while (i < n && nums[i] == nums[i-1] +1) s += nums[i++];
unordered_set<int> st(nums.begin(), nums.end());
int x = s;
while (st.count(x)) ++x;
return x;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
classSolution {
publicintmissingInteger(int[] nums) {
int n = nums.length, i = 1, s = nums[0];
while (i < n && nums[i]== nums[i-1]+ 1) s += nums[i++];
Set<Integer> st =new HashSet<>();
for (int x : nums) st.add(x);
int x = s;
while (st.contains(x)) x++;
return x;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmissingInteger(self, nums):
i, s =1, nums[0]
while i < len(nums) and nums[i] == nums[i-1] +1:
s += nums[i]
i +=1 st = set(nums)
x = s
while x in st:
x +=1return x