Skip to content

Commit ad6bc22

Browse files
committed
704.Binary Search.
1 parent a35ac3f commit ad6bc22

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
3+
4+
You must write an algorithm with O(log n) runtime complexity.
5+
6+
7+
8+
Example 1:
9+
Input: nums = [-1,0,3,5,9,12], target = 9
10+
Output: 4
11+
Explanation: 9 exists in nums and its index is 4
12+
13+
Example 2:
14+
Input: nums = [-1,0,3,5,9,12], target = 2
15+
Output: -1
16+
Explanation: 2 does not exist in nums so return -1
17+
18+
19+
Constraints:
20+
- 1 <= nums.length <= 104
21+
- -104 < nums[i], target < 104
22+
- All the integers in nums are unique.
23+
- nums is sorted in ascending order.
24+
*/
25+
class Solution {
26+
func search(_ nums: [Int], _ target: Int) -> Int {
27+
var left = 0
28+
var right = nums.count - 1
29+
while left <= right {
30+
var middle = (left + right) / 2
31+
if nums[middle] == target {
32+
return middle
33+
} else if nums[middle] > target {
34+
right = middle - 1
35+
} else {
36+
left = middle + 1
37+
}
38+
}
39+
return -1
40+
}
41+
}
42+
43+
let s = Solution()
44+
let r = s.search([5], 5)
45+
print(r)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/704.Binary Search.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
123. [Count Binary Substrings](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/696.Count%20Binary%20Substrings.playground/Contents.swift)
128128
124. [Degree of an Array](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/697.Degree%20of%20an%20Array.playground/Contents.swift)
129129
125. [Long Pressed Name](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/925.Long%20Pressed%20Name.playground/Contents.swift)
130+
126. [Binary Search](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/704.Binary%20Search.playground/Contents.swift)
130131

131132
#### Medium
132133

0 commit comments

Comments
 (0)