算法挑战100天 - one (easy)
2020-08-25 本文已影响0人
holmes000
一天一道算法题,按类别划分
要求:简单,中等难度要自己写一版,然后再跟最优解对比,说出差异点;困难难度,无计可施时可参考最优解;
题目:都以链接为准,一般时力扣的;
类别:数组
题目:https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof/
我的解:
public int missingNumber(int[] nums) {
Integer result = null;
if(nums[0] != 0) {
return 0;
}
int temp = 0;
for (int i = 0; i < nums.length; i++) {
if ((nums[i] - temp) > 1) {
result = nums[i] - 1;
break;
}
temp = nums[i];
result = temp + 1;
}
return result;
}
最优解:
1)顺序查找:
public int missingNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if(nums[i] != i){
return i;
}
}
return nums.length;
}
2)二分法:
public int missingNumber(int[] nums) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (mid == nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
差异点:
- 没考虑过利用索引下标做标示以区分,而用了临时变量;
只看了数学逻辑,没考虑数据结构特性; - 没考虑可以用二分法;