# C#LeetCode刷题之#35-搜索插入位置（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.

Input: [1,3,5,6], 5

Output: 2

Input: [1,3,5,6], 2

Input: 1

Input: [1,3,5,6], 7

Input: 4

Input: [1,3,5,6], 0

Input: 0

```public class Program {

public static void Main(string[] args) {
int[] nums = { 1, 3, 5, 6 };

Console.WriteLine(SearchInsert(nums, 2));
Console.WriteLine(SearchInsert2(nums, 6));

}

private static int SearchInsert(int[] nums, int target) {
for(int i = 0; i < nums.Length; i++) {
if(nums[i] >= target) return i;
}
return nums.Length;
}

private static int SearchInsert2(int[] nums, int target) {
int mid = 0, low = 0;
int high = nums.Length - 1;

while(low <= high) {
mid = low + (high - low) / 2;

if(nums[mid] == target) {
return mid;
} else if(nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return low;
}

}```

```1
3```