Skip to content

Commit

Permalink
go & python implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed Apr 27, 2019
1 parent a2150f7 commit 770f1f6
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package findboth

func bisecLeft(nums []int, target int) int {
left, right := 0, len(nums)
var mid int
for left < right {
mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else {
right = mid
}
}
return left
}

func bisecRight(nums []int, target int) int {
left, right := 0, len(nums)
var mid int
for left < right {
mid = (left + right) / 2
if nums[mid] <= target {
left = mid + 1
} else {
right = mid
}
}
return left
}

func searchRange(nums []int, target int) []int {

left := bisecLeft(nums, target)
if left == len(nums) ||
nums[left] != target {
return []int{-1, -1}
}
right := bisecRight(nums[left+1:], target)
return []int{left, left + right}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from bisect import bisect, bisect_left


class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
left = bisect_left(nums, target)
if left != len(nums) and nums[left] == target:
right = bisect(nums, target, left)
return left, right - 1
else:
return -1, -1
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package findleft

/* merely 1 function. merely find left
cannot judge in besecLeft() whether nums[left]==target
because we search target+1 to get the right position
*/

func bisecLeft(nums []int, target int) int {
// 这个函数相当于 python中的bisect.bisect_left
left, right := 0, len(nums)
var mid int
for left < right {
mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else {
right = mid
}
}
return left
}

func searchRange(nums []int, target int) []int {
left := bisecLeft(nums, target)
if left == len(nums) ||
nums[left] != target {
return []int{-1, -1}
}
right := bisecLeft(nums[left+1:], target+1)
return []int{left, left + right}
}

0 comments on commit 770f1f6

Please sign in to comment.