public class Solution { public int SearchInsert(int[] nums, int target) { for (int i = 0; i < nums.Length; i++) { if (nums[i] >= target) { return i; } } return nums.Length; } }
https://leetcode.com/problems/search-insert-position/#/description
补充一个Java的实现:
1 class Solution { 2 public int searchInsert(int[] nums, int target) { 3 int n = nums.length; 4 if (n == 0){ 5 return 0; 6 } 7 for(int i=0;i<n;i++){ 8 int cur = nums[i]; 9 if(cur < target){ 10 continue; 11 }else{ 12 return i; 13 } 14 } 15 return n; 16 } 17 }
Java版本代码,使用二分查找:
1 class Solution { 2 public int searchInsert(int[] nums, int target) { 3 int n = nums.length; 4 if (n == 0){ 5 return 0; 6 } 7 if(target < nums[0]){ 8 return 0; 9 } 10 if(target > nums[n-1]){ 11 return n; 12 } 13 int low = 0; 14 int high = n; 15 while(low <= high){ 16 int mid = (high + low) / 2; 17 int cur = nums[mid]; 18 if(cur == target){ 19 return mid; 20 }else if(cur < target){ 21 low = mid + 1; 22 }else{ 23 high = mid - 1; 24 } 25 } 26 return low; 27 } 28 }