[LeetCode35]Search Insert Position
来源:互联网 发布:视觉检测软件 编辑:程序博客网 时间:2024/05/22 12:57
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; else l = m+1; } return l; }
0 0
- [LeetCode35]Search Insert Position
- Leetcode35 Search Insert Position
- [LeetCode35]Search Insert Position
- Leetcode35: Search Insert Position
- Leetcode35. Search Insert Position
- leetcode35: Search Insert Position
- Leetcode35. Search Insert Position
- LeetCode35. Search Insert Position
- leetcode35~Search Insert Position
- leetcode35. Search Insert Position
- leetcode35-search insert position
- LeetCode35. Search Insert Position
- Leetcode35.Search Insert Position
- leetcode35. Search Insert Position
- LeetCode35——Search Insert Position
- LeetCode35. Search Insert Position轻松解决
- 【LeetCode35】【Search Insert Position】二分法查找
- LeetCode: Search Insert Position
- 【LeetCode】Length of Last Word
- Delphi2006连接Mysql5.1
- test
- 动态创建clientdataset的表定义_delphi教程
- 详解JavaScript对象
- [LeetCode35]Search Insert Position
- LeetCode 22. Merge k Sorted Lists
- STL: priority_queue学习
- 醉牛记牌器
- 你的覅U盾是否科技
- 【JavaScript 封装库】Prototype 原型版发布!
- [LeetCode36]Valid Sudoku
- 【JavaScript 封装库】BETA 1.0 测试版发布!
- 苍狼敏捷需求用例分析方法简介并讲义下载