-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSearchInsertPosition.cs
executable file
·61 lines (57 loc) · 3.35 KB
/
SearchInsertPosition.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Source : https://leetcode.com/problems/search-insert-position/
// Author : codeyu
// Date : Monday, October 17, 2016 7:37:43 PM
/**********************************************************************************
*
* 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.
*
*
* Here are few examples.
* [1,3,5,6], 5 → 2
* [1,3,5,6], 2 → 1
* [1,3,5,6], 7 → 4
* [1,3,5,6], 0 → 0
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution035
{
public static int SearchInsert(int[] nums, int target)
{
if(nums != null && nums.Length > 0)
{
var left = 0;
var right = nums.Length - 1;
while(left <= right)
{
var mid = left + (right - left) / 2;
if(nums[mid] == target)
{
return mid;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
if(left > right)
{
return left;
}
return left == 0 ? 0 : nums.Length;
}
return -1;
}
}
}