645. Set Mismatch
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 01, 2024
Last updated : July 19, 2024
Related Topics : Array, Hash Table, Bit Manipulation, Sorting
Acceptance Rate : 44.68 %
// Not that good of a runtime
class Solution {
public int[] findErrorNums(int[] nums) {
int intendedSum = ((1 + nums.length) * nums.length) / 2;
int actualSum = 0;
HashSet<Integer> seenSet = new HashSet<>();
int repeat = -1;
for (int i: nums) {
actualSum += i;
if (seenSet.contains(i)) {
repeat = i;
}
seenSet.add(i);
}
return new int[]{repeat, (repeat + intendedSum - actualSum)};
}
}
// Consistently 5% percentile --> bad runtime but works
class Solution {
public int[] findErrorNums(int[] nums) {
byte[] corrects = new byte[nums.length];
int dupe = -1;
for (int i = 0; i < nums.length; i++) {
corrects[nums[i] - 1] += 1;
if (corrects[nums[i] - 1] == 2) {
dupe = nums[i];
}
}
for (int i = 0; i < corrects.length; i++) {
System.out.println(corrects[i]);
}
int index = 0;
while (true) {
if (corrects[index] == 0) {
return new int[]{dupe, index + 1};
}
index++;
}
}
}
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
correctSum = ((1 + len(nums)) * len(nums)) // 2
currentSum = sum(nums)
dupeVal = -1
pastVals = set()
for i in range(0, len(nums)) :
if nums[i] in pastVals :
dupeVal = nums[i]
break
pastVals.add(nums[i])
print(dupeVal, correctSum, currentSum)
missingVal = dupeVal + correctSum - currentSum
return [dupeVal, missingVal]