Last active
August 28, 2017 22:27
-
-
Save cixuuz/179b3d288dbc6d2fa303290046394fe7 to your computer and use it in GitHub Desktop.
[645. Set Mismatch] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
// O(n) O(n) | |
public int[] findErrorNums(int[] nums) { | |
boolean[] res = new boolean[nums.length]; | |
int dup = -1; | |
int miss = -1; | |
for (int i = 0 ; i < nums.length; i++) { | |
if (res[nums[i]-1]) { | |
dup = nums[i]; | |
} else { | |
res[nums[i]-1] = true; | |
} | |
} | |
for (int i = 0 ; i < res.length; i++ ) { | |
if (!res[i]) miss = i+1; | |
} | |
return new int[] {dup, miss}; | |
} | |
} | |
class Solution1 { | |
// O(n) O(1) | |
public int[] findErrorNums(int[] nums) { | |
int[] res = new int[2]; | |
for (int i : nums ) { | |
if (nums[Math.abs(i) - 1] < 0) { | |
res[0] = Math.abs(i); | |
} else { | |
nums[Math.abs(i) - 1] *= -1; | |
} | |
} | |
for (int i = 0 ; i < nums.length; i++ ) { | |
if (nums[i] > 0) res[1] = i+1; | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment