From 980fa06605e73c5a47d690c6f70852d1d5498b1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=9F=8F=E6=9E=97?= <37291290+luckydog612@users.noreply.github.com> Date: Tue, 30 Oct 2018 11:03:47 +0800 Subject: [PATCH] Create binarysearch2.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 16 | 二分查找(下) --- go/binarysearch2.go | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 go/binarysearch2.go diff --git a/go/binarysearch2.go b/go/binarysearch2.go new file mode 100644 index 0000000..ef2549e --- /dev/null +++ b/go/binarysearch2.go @@ -0,0 +1,90 @@ +package binarySearch + +//查找第一个值等于给定值得元素 +func BinarySearch2(nums []int, value int) int { + length := len(nums) + start := 0 + end := length - 1 + for start <= end { + mid := (start + end) / 2 + if nums[mid] > value { + end = mid - 1 + } else if nums[mid] < value { + start = mid + 1 + } else { + for mid >= 0 { + if nums[mid-1] == value { + mid-- + } else { + return mid + } + } + } + } + return -1 +} + +// 查找最后一个值等于给定值的元素 +func BinarySearch3(nums []int, value int) int { + start := 0 + end := len(nums) - 1 + for start <= end { + mid := (start + end) / 2 + if nums[mid] > value { + end = mid - 1 + } else if nums[mid] < value { + start = mid + 1 + } else { + for mid < len(nums) { + if nums[mid+1] == value { + mid++ + } else { + return mid + } + } + } + } + return -1 +} + +// 查找第一个大于等于给定值的元素 +func BinarySearch4(nums []int, value int) int { + start := 0 + end := len(nums) - 1 + for start <= end { + mid := (start + end) >> 1 + if nums[mid] < value { + start = mid + 1 + } else { + for mid >= 0 { + if nums[mid-1] >= value { + mid-- + } else { + return mid + } + } + } + } + return -1 +} + +// 查找最后一个小于等于给定值的元素 +func BinarySearch5(nums []int, value int) int { + start := 0 + end := len(nums) - 1 + for start <= end { + mid := (start + end) >> 1 + if nums[mid] > value { + end = mid - 1 + } else { + for mid < len(nums) { + if nums[mid+1] <= value { + mid++ + } else { + return mid + } + } + } + } + return -1 +}