Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

寻找数组内一个可插入的位置

  • Loading branch information...
commit eb86940db27cb48f1697583d8f04118d7b8e1b23 1 parent 75c3e1e
= authored
Showing with 42 additions and 0 deletions.
  1. +42 −0 search-insert-position.cpp
View
42 search-insert-position.cpp
@@ -0,0 +1,42 @@
+
+
+
+// http://oj.leetcode.com/problems/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
+
+
+class Solution {
+public:
+ int searchInsert(int A[], int n, int target) {
+ if(A==NULL || n<=0) {
+ return 0;
+ }
+
+ return binarySearch(A, 0, n-1, target);
+ }
+
+ int binarySearch(int A[], int beg, int end, int target) {
+ if(beg>end) {
+ return beg;
+ }
+
+ int mid = (beg+end) / 2;
+
+ if(target==A[mid]) {
+ return mid;
+ }else if(target>A[mid]) {
+ return binarySearch(A, mid+1, end, target);
+ }else {
+ return binarySearch(A, beg, mid-1, target);
+ }
+ }
+};
Please sign in to comment.
Something went wrong with that request. Please try again.