[leetcode]Set Mismatch
problem
code
possible cases
// cases after sorted in ascending order
[2, 3, 3, 4, 5, 6] => [3, 1]
[1, 2, 3, 3, 5, 6] => [3, 4]
[1, 2, 4, 4, 5, 6] => [4, 3]
[1, 2, 2, 3, 4, 5] => [2, 6]
1st try: with Map
It must be better to use duplicate, missing variables other than new int[2] cuz they are more clear to read the code.
class Solution {
public int[] findErrorNums(int[] nums) {
Map<Integer, Integer> map = new HashMap();
int[] ans = new int[2]; // [duplicate, missing];
for (int n: nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
for (int i = 1; i <= nums.length; i++) {
if (map.containsKey(i)) {
if (map.get(i) == 2)
ans[0] = i;
} else {
ans[1] = i;
}
}
return ans;
}
}
Time: O(N); two for loop iterating N
Space: O(N); HashMap contains N elements at most
2nd try: sorting
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function(nums) {
nums.sort((a, b) => a - b);
// console.log(nums);
let duplicate = -1;
let missing = 1; // for the case when nums[0] != 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
duplicate = nums[i];
} else if (nums[i] > nums[i - 1] + 1) {
//when nums[0] != 1 => never
missing = nums[i - 1] + 1;
}
}
return [duplicate, nums[nums.length - 1] == nums.length ? missing : nums.length];
}
Time: O(nlogn); sorting
Space: O(1)
3rd try: brute force
class Solution {
public int[] findErrorNums(int[] nums) {
int[] ans = new int[2]; // [duplicate, missing];
for (int i = 1; i <= nums.length; i++) { //
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (i == nums[j])
count++;
}
if (count == 2)
ans[0] = i;
else if (count == 0)
ans[1] = i;
if (nums[0] != 0 && nums[1] != 0)
break;
}
return ans;
}
}
Time: O(N^2)
Author And Source
이 문제에 관하여([leetcode]Set Mismatch), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@victor/leetcode-opbhc3k8저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)