在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a sorted (in ascending order) integer array Example 1: Input: Example 2: Input: Note:
给定一个 示例 1: 输入: 示例 2: 输入: 提示:
292ms 1 class Solution { 2 func search(_ nums: [Int], _ target: Int) -> Int { 3 4 var left = 0 5 var right = nums.count - 1 6 var mid = (left + right) / 2 7 8 while left <= right { 9 if target == nums[mid] { 10 return mid 11 } else if target == nums[left] { 12 return left 13 } else if target == nums[right] { 14 return right 15 } else if target > nums[left] && target < nums[mid] { 16 right = mid - 1 17 mid = (left + mid) / 2 18 left += 1 19 } else if target > nums[mid] && target < nums[right] { 20 left = mid + 1 21 mid = (mid + right) / 2 22 right -= 1 23 } else { 24 return -1 25 } 26 } 27 28 return -1 29 } 30 } Runtime: 296 ms
Memory Usage: 18.9 MB
1 class Solution { 2 func search(_ nums: [Int], _ target: Int) -> Int { 3 var low = 0 4 var high = nums.count - 1 5 var mid = (low + high) >> 1 6 7 while low <= high { 8 let val = nums[mid] 9 if target == val { 10 return mid 11 } else if target < val { 12 high = mid - 1 13 } else { 14 low = mid + 1 15 } 16 mid = (low + high) >> 1 17 } 18 return -1 19 } 20 } 312ms 1 class Solution { 2 func search(_ nums: [Int], _ target: Int) -> Int { 3 if nums.count == 1 {return nums[0] == target ? 0 : -1} 4 else if nums.count == 0 {return -1} 5 6 return binarySearch (nums, target, 0, nums.count-1) 7 } 8 9 func binarySearch(_ nums:[Int], _ target: Int, _ l: Int, _ r: Int) -> Int { 10 if (r >= l) { 11 var mid = l + (r-l)/2 12 if nums[mid] == target {return mid} 13 else if nums[mid] > target {return binarySearch(nums, target, l, mid-1) } 14 else {return binarySearch(nums, target, mid+1, r)} 15 } 16 return -1 17 } 18 } 352ms 1 class Solution { 2 3 var start = 0; 4 var end = 0; 5 6 var center: Int { 7 return (end + start) >> 1 8 } 9 10 func search(_ nums: [Int], _ target: Int) -> Int { 11 end = nums.count 12 while start != end - 1 { 13 if nums[center] == target { 14 return center 15 }else if nums[center] < target { 16 start = center 17 }else { 18 end = center 19 } 20 } 21 return nums[center] == target ? center : -1 22 } 23 } 452ms 1 class Solution { 2 func search(_ nums: [Int], _ target: Int) -> Int { 3 func search(_ l: Int, _ r: Int) -> Int { 4 if l == r && nums[l] != target { 5 return -1 6 } 7 8 let mid = l + (r + 1 - l) / 2 9 10 if nums[mid] == target { 11 return mid 12 } else if nums[mid] > target { 13 return search(l, mid - 1) 14 } else { 15 return search(mid, r) 16 } 17 } 18 19 return search(0, nums.count - 1) 20 } 21 }
|
请发表评论