Created
November 23, 2014 15:35
-
-
Save chuchao333/c8134f2edaa8ec448697 to your computer and use it in GitHub Desktop.
Search Insert Position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int searchInsert(int A[], int n, int target) { | |
int low = 0, high = n; | |
// search in the interval A[low, high) | |
while (low < high) { | |
// loop invariant | |
// 1) 0 <= low < high <= n | |
// 2) (low == 0 || A[low - 1] < target) | |
// 3) (high == n || A[high] > target) | |
auto mid = (high - low) / 2 + low; | |
if (A[mid] < target) { | |
low = mid + 1; | |
} else if (A[mid] > target) { | |
high = mid; | |
} else { | |
return mid; | |
} | |
} | |
return low; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment