昨天看到网上有人说leetcode不能提交成功就好,要想运行时间短的算法。今天有点时间就对前面的题想想吧。主要还是看别人的,但是提交之后发现和我的差别不是很大,1ms。
34题Java代码,思路是用二分法。二分法思想很简单,就不多说了。代码转自http://blog.csdn.net/lilong_dream/article/details/22893675
public int[] searchRange(int[] A, int target) {
int left = 0;
int right = A.length - 1;
int[] result = { -1, -1 };
while (left <= right) {
int mid = (left + right) / 2;
if (A[mid] > target) {
right = mid - 1;
} else if (A[mid] < target) {
left = mid + 1;
} else {
result[0] = mid;
result[1] = mid;
int i = mid - 1;
while (i >= 0 && A[i] == target) {
result[0] = i;
--i;
}
i = mid + 1;
while (i < A.length && A[i] == target) {
result[1] = i;
++i;
}
break;
}
}
return result;
}
提交之后大概击败26%,比我的快了1ms。
35题还是利用二分法。Java代码转自http://blog.csdn.net/u012848330/article/details/52145150
public class Solution {
public int searchInsert(int[] nums, int target) {
return binarySearch(nums,target,0,nums.length-1);
}
private int binarySearch(int[] nums, int target, int left, int right) {
// TODO Auto-generated method stub
if(left > right)
return -1;
if(left == right){
if(nums[left] >= target){
return left;
}else{
return right+1;
}
}
int mid = (left + right)/2;
if(target < nums[mid]){
return binarySearch(nums,target,left,mid);
}else if(target == nums[mid]){
return mid;
}else{
return binarySearch(nums,target,mid+1,right);
}
}
}
提交之后还是比我的快了1ms。这个思路算是不错的了。两个题都是二分法。