Skip to content

Commit b4a9ed7

Browse files
committed
Modified question 35. Search Insert Position: 1. added notes, 2. shorten the variable name length.
1 parent 3b9286e commit b4a9ed7

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed
Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
1+
// keynote:
2+
// 1. start from boundary checking
3+
// 2. use simple real case to determine the index in the end
14
public class Solution {
25
public int SearchInsert(int[] nums, int target) {
3-
if (nums == null || nums.Length == 0) return 0;
4-
int start = 0;
5-
int end = nums.Length - 1;
6-
while (start + 1 < end) {
7-
int mid = start + (end - start) / 2;
8-
if (nums[mid] == target) {
9-
return mid;
10-
} else if (nums[mid] < target) {
11-
start = mid;
6+
if (nums == null || nums.Length == 0) {
7+
return 0;
8+
}
9+
int l = 0, r = nums.Length - 1, m;
10+
while (l + 1 < r) {
11+
m = l + (r - l) / 2;
12+
if (nums[m] == target) {
13+
return m;
14+
} else if (nums[m] < target) {
15+
l = m + 1;
1216
} else {
13-
end = mid;
17+
r = m - 1;
1418
}
1519
}
16-
if (target <= nums[start]) return start;
17-
if (nums[start] < target && target <= nums[end]) return end;
18-
return end+1;
20+
if (target <= nums[l]) {
21+
return l;
22+
}
23+
if (target > nums[r]) {
24+
return r + 1;
25+
}
26+
return r;
1927
}
2028
}

0 commit comments

Comments
 (0)