一次过
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int left = 0; 7 int right = n - 1; 8 int mid; 9 while (left <= right) { 10 mid = (left + right) / 2; 11 if (target == A[mid]) return mid; 12 if (target > A[mid]) left = mid + 1; 13 else right = mid - 1; 14 } 15 return right + 1; 16 } 17 };
C#
1 public class Solution { 2 public int SearchInsert(int[] nums, int target) { 3 int left = 0, right = nums.Length - 1; 4 while (left <= right) { 5 int mid = (left + right) / 2; 6 if (target == nums[mid]) return mid; 7 if (target > nums[mid]) left = mid + 1; 8 else right = mid - 1; 9 } 10 return right + 1; 11 } 12 }