Skip to content

Commit 9552add

Browse files
Search Insert Position
1 parent a4bcd7b commit 9552add

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ Your ideas/fixes/algorithms are more than welcome!
213213
|41|[First Missing Positive](https://leetcode.com/problems/first-missing-positive/)|[Solution](../../blob/master/src/stevesun/algorithms/FirstMissingPositive.java)|O(n)|O(1)|Hard|
214214
|39|[Combination Sum](https://leetcode.com/problems/combination-sum/)|[Solution](../../blob/master/src/stevesun/algorithms/CombinationSum.java)|O(k*n^k)|O(k)|Medium|Backtracking
215215
|38|[Count and Say](https://leetcode.com/problems/count-and-say/)|[Solution](../../blob/master/src/stevesun/algorithms/CountandSay.java)|O(n*2^n)|O(2^n)|Easy| Recursion, LinkedList
216+
|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)|[Solution](../../blob/master/src/stevesun/algorithms/SearchInsertPosition.java)|O(n)|O(1)|Medium|Array
216217
|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)|[Solution](../../blob/master/src/stevesun/algorithms/SearchForARange.java)|O(logn)|O(1)|Medium|Array, Binary Search
217218
|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)|[Solution](../../blob/master/src/stevesun/algorithms/SearchinRotatedSortedArray.java)|O(logn)|O(1)|Hard|Binary Search
218219
|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)|[Solution](../../blob/master/src/stevesun/algorithms/LongestValidParentheses.java)|O(n)|O(n)|Hard|Stack, DP
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package stevesun.algorithms;
2+
3+
/**
4+
* 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.
5+
6+
You may assume no duplicates in the array.
7+
8+
Here are few examples.
9+
[1,3,5,6], 5 → 2
10+
[1,3,5,6], 2 → 1
11+
[1,3,5,6], 7 → 4
12+
[1,3,5,6], 0 → 0
13+
*/
14+
public class SearchInsertPosition {
15+
16+
public int searchInsert(int[] A, int target) {
17+
int len = A.length;
18+
if (len == 0)
19+
return 0;
20+
else {
21+
for (int i = 0; i < len; i++) {
22+
if (A[0] > target)
23+
return 0;
24+
else if (A[len - 1] < target)
25+
return len;
26+
else if (A[i] == target)
27+
return i;
28+
else if (A[i] < target && A[i + 1] > target)
29+
return i + 1;
30+
}
31+
return len;
32+
}
33+
}
34+
35+
}

0 commit comments

Comments
 (0)