标签:leetcode
题意: 给出一个target找出他在有序数组中的位置public int searchInsert1(int[] A, int target) {//直接遍历 算法O(N) int i = 0; if(target < A[0]) return 0; if(target > A[A.length - 1]) return A.length; for(; i < A.length; ++ i){ if(A[i] == target) return i; if(target < A[i+1] && target > A[i]) return i + 1; } return i; }
思路2: 二分法,注意处理边界问题,算法复杂度 O(log(N))
代码2:
public int searchInsert(int[] A, int target) {//二分法 算法O(log(N)) int i = 0; if(target <= A[0]) return 0; if(target > A[A.length - 1]) return A.length; if(target == A[A.length - 1]) return A.length - 1; int start = 0, end = A.length - 1, mid; while (start < end){ mid = start + (end - start) / 2; if(A[mid] < target){ start = mid + 1; }else if(A[mid] > target){ end = mid -1; }else { return mid; } } if(start >= end){ if(target > A[end]) { return end + 1; } else if(target == A[end]) return end; else { return end; } } return i; }
[LeetCode] Search Insert Position
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44871469