Skip to content

Instantly share code, notes, and snippets.

@chuchao333
Created November 23, 2014 15:35
Show Gist options
  • Save chuchao333/c8134f2edaa8ec448697 to your computer and use it in GitHub Desktop.
Save chuchao333/c8134f2edaa8ec448697 to your computer and use it in GitHub Desktop.
Search Insert Position
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