0704-leetcode演算法實現之二分查詢-bianarySearch-python&golang實現
阿新 • • 發佈:2021-10-13
給定一個n個元素有序的(升序)整型陣列nums 和一個目標值target ,寫一個函式搜尋nums中的 target,如果目標值存在返回下標,否則返回 -1。
示例 1:
輸入: nums = [-1,0,3,5,9,12], target = 9
輸出: 4
解釋: 9 出現在 nums 中並且下標為 4
示例2:
輸入: nums = [-1,0,3,5,9,12], target = 2
輸出: -1
解釋: 2 不存在 nums 中因此返回 -1
提示:
你可以假設 nums中的所有元素是不重複的。
n將在[1, 10000]之間。
nums的每個元素都將在[-9999, 9999]之間。
來源:力扣(LeetCode)
連結: https://leetcode-cn.com/problems/binary-search
python
class Solution: def bianarySearch(self, nums: [int], target: int) -> int: """ 二分查詢,時間O(logn),空間O(1) :param nums: [int] :param target: int :return: int """ if len(nums) == 0: return -1 left = 0 right = len(nums) - 1 while left <= right: mid = int((left+right)/2) if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid - 1 else: return mid return -1 if __name__ == "__main__": nums1 = [1,3,5,7,8,9,13,15,16] nums2 = [] target1 = 10 target2 = 13 test = Solution() print(test.bianarySearch(nums2, target1)) print(test.bianarySearch(nums1, target1)) print(test.bianarySearch(nums1, target2))
golang
package main import "fmt" func main() { var nums = []int{1, 3, 5, 6, 7, 9, 10, 23, 25} var target int = 10 res := bianarySearch(nums, target) fmt.Println(res) } func bianarySearch(nums []int, target int) int { if len(nums) == 0 { return -1 } var left int = 0 var right int = len(nums) -1 for left <= right { mid := (left + right) / 2 if nums[mid] < target { left = mid + 1 } else if nums[mid] > target { right = mid - 1 } else { return mid } } return -1 }