本文主要是介绍[LeetCode35]Search Insert Position,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
Analysis:
could use binary search, there has a additional condition if(mid>left && A[mid]>target && A[mid-1]<target)
Java
public int searchInsert(int[] A, int target) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.int low = 0;int high = A.length-1;if(target < A[0])return 0;if(target > A[A.length-1])return A.length;while(low <= high){int mid = (low+high)/2;if(A[mid]==target)return mid;if(mid>1 && A[mid]>target && A[mid-1]<target) return mid;if(A[mid]>target)high = mid-1;elselow = mid+1;}return 1;}
update
public int searchInsert(int[] nums, int target) {int len = nums.length;if(len<=0) return 0;if(target<=nums[0]) return 0;if(target>nums[len-1]) return len;int left = 0;int right = len-1;while(left<=right) {int mid = left + (right-left)/2;if(nums[mid] == target) return mid;if(nums[mid] > target) {if(target>nums[mid-1]) return mid;else right = mid-1;}else {if(target<nums[mid+1]) return mid+1;else left = mid+1;}}return left;}
c++
int searchInsert(int A[], int n, int target) {if(A == NULL|| target<A[0]) return 0;if(target>A[n-1]) return n;int l = 0;int r = n-1;while(l<=r){int m = (l+r)/2;if(A[m]==target) return m;if(m>l&& A[m]>target && A[m-1]<target) return m;if(A[m]>target)r = m-1;elsel = m+1;}return l; }
这篇关于[LeetCode35]Search Insert Position的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!