- Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathSearchInsertPosition.cs
More file actions
Latest commit
executable file
·61 lines (57 loc) · 3.35 KB
/
Copy pathSearchInsertPosition.cs
File metadata and controls
executable file
·61 lines (57 loc) · 3.35 KB
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
*
*
**********************************************************************************/
usingSystem;
usingSystem.Collections.Generic;
usingAlgorithms.Utils;
namespaceAlgorithms
{
publicclassSolution035
{
publicstaticintSearchInsert(int[]nums,inttarget)
{
if(nums!=null&&nums.Length>0)
{
varleft=0;
varright=nums.Length-1;
while(left<=right)
{
varmid=left+(right-left)/2;
if(nums[mid]==target)
{
returnmid;
}
elseif(nums[mid]<target)
{
left=mid+1;
}
else
{
right=mid-1;
}
}
if(left>right)
{
returnleft;
}
returnleft==0?0:nums.Length;
}
return-1;
}
}
}