二分法 查找

2020-06-18 18:20 更新

題目

給定一個 n 個元素有序的(升序)整型數(shù)組 nums 和一個目標(biāo)值 target ,寫一個函數(shù)搜索 nums 中的 target,如果目標(biāo)值存在返回下標(biāo),否則返回 -1。

示例 1:

輸入: nums = [-1,0,3,5,9,12], target = 9 輸出: 4 解釋: 9 出現(xiàn)在 nums 中并且下標(biāo)為 4

示例 2:

輸入: nums = [-1,0,3,5,9,12], target = 2 輸出: -1 解釋: 2 不存在 nums 中因此返回 -1

提示:

你可以假設(shè) nums 中的所有元素是不重復(fù)的。 n 將在 [1, 10000]之間。 nums 的每個元素都將在 [-9999, 9999]之間。

經(jīng)典解法

1.引入開頭start=0,end=nums.length-1

2.因為是升序,所以如果中間的值也就是 half=start+(end-start)/2;nums[half]大于target的話說明target在half的后面,所以讓start=half+1從后半段中尋找

同理,小于的時候從end=half-1前半段查找

3.直到找到返回下標(biāo),如果沒有找到就會產(chǎn)生start>end,跳出while

  1. class Solution {
  2. public int search(int[] nums, int target) {
  3. int start=0,end=nums.length-1;
  4. int half=0;
  5. while(start<=end){
  6. half=start+(end-start)/2;
  7. if(nums[half]==target) return half;
  8. else if(nums[half]<target) start =half +1;
  9. else if(nums[half]>target) end =half -1;
  10. }
  11. return -1;
  12. }
  13. }

解法二:Python

  1. class Solution:
  2. def search(self, nums: List[int], target: int) -> int:
  3. left, right = 0, len(nums) - 1
  4. while left <= right:
  5. pivot = left + (right - left) // 2
  6. if nums[pivot] == target:
  7. return pivot
  8. if target < nums[pivot]:
  9. right = pivot - 1
  10. else:
  11. left = pivot + 1
  12. return -1
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號