My code:
public class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int n = nums.length;
int sum = (1 + n) * n / 2;
for (int i = 0; i < nums.length; i++)
sum -= nums[i];
return sum;
}
}
My test result:
這次題目感覺挺簡單的,先用告訴公式算出總和,然后一個個減,失去的那個,就是最后sum還剩下的值。
然后網(wǎng)上看了,還有一種 bit manipulation的做法。感覺沒必要啊,速度也沒我快。
盡管我也不能理解他的算法。把代碼貼在這里,以后有需要的時候可以看。
public class Solution {
public int missingNumber(int[] nums) {
int check = 0;
for (int i=0; i<nums.length; i++) {
check ^= nums[i] ^ i + 1;
}
return check;
}
}
**
總結(jié): Array, bit manipulation
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0)
return -1;
int sum = 0;
for (int i = 0; i < nums.length; i++)
sum += nums[i];
int n = nums.length;
return (1 + n) * n / 2 - sum;
}
}
Anyway, Good luck, Richardo!
想多了,沒想出怎么做。
原來如此簡單。
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int i = 0;
int pre = -1;
while (i < nums.length) {
if (nums[i] == nums.length) {
pre = i;
i++;
}
else if (nums[nums[i]] == nums[i]) {
i++;
}
else {
int temp = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = temp;
}
}
if (pre == -1) {
return nums.length;
}
else {
return pre;
}
}
}
還可以這么做,雖然更復(fù)雜些。
Anyway, Good luck, Richardo! -- 09/12/2016