SetMismatch [source code]
public class SetMismatch {
static
/******************************************************************************/
public class Solution {
public int[] findErrorNums(int[] nums) {
int[] res = new int[2];
int n = nums.length;
for (int i = 0; i < n; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
res[0] = index + 1;
} else {
nums[index] = - nums[index];
}
}
for (int i = 0; i < n; i++)
if (nums[i] > 0)
res[1] = i + 1;
return res;
}
}
/******************************************************************************/
public static void main(String[] args) {
SetMismatch.Solution tester = new SetMismatch.Solution();
int[][] inputs = {
{1,2,2,4}, {2,3},
};
for (int i = 0; i < inputs.length / 2; i++) {
int[] nums = inputs[2 * i];
String expected = Printer.array(inputs[1 + 2 * i]);
String output = Printer.array(tester.findErrorNums(nums));
System.out.println(Printer.seperator());
System.out.println(Printer.wrapColor(Printer.array(nums), "magenta") + " -> " + output + Printer.wrapColor(", expected: " + expected, output.equals(expected) ? "green" : "red"));
}
}
}
又是一个value domain equals index domain的题目;
比较简单的题目, 不要忘记+/-1就行了; 因为严格来说两个domain并不想等, 还是有1的差值的;
最后的速度是10ms (100%), 不过因为是新题目, 所以其实没有太大的参考意义;
Problem Description
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
Note:
The given array size will in the range [2, 10000].
The given array's numbers won't have any order.
Difficulty:Easy
Total Accepted:2.4K
Total Submissions:5.7K
Contributor: rishb_rex
Companies
amazon
Related Topics
hash table math
Similar Questions
Find the Duplicate Number