Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

find first and last position of element in sorted array #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ continually updating 😃.

### Binary Search
* [704. Binary Search](./src/0704_binary_search/binary_search.go)
* [34. Find First and Last Position of Element in Sorted Array](./src/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go)   *`array;`*  *`binary search`*

<details>
</details>
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
34. Find First and Last Position of Element in Sorted Array
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].
*/
// time: 2018年12月20日

package findfirstandlastpositionofelementinsortedarray

// binary search
// time complexity: O(logn)
// space complexity: O(1)
func searchRange(nums []int, target int) []int {
lowerIndex := firstOccurance(nums, target)
first := -1
if lowerIndex != len(nums) && target == nums[lowerIndex] {
first = lowerIndex
}

upperIndex := lastOccurance(nums, target)
last := -1
if upperIndex == len(nums) && len(nums) > 0 && target == nums[len(nums)-1] {
last = len(nums) - 1
} else if upperIndex != len(nums) && upperIndex > 0 && target == nums[upperIndex-1] {
last = upperIndex - 1
}
return []int{first, last}
}

func firstOccurance(nums []int, target int) int {
var (
l int
r = len(nums)
)

for l != r { // 夹逼思想
mid := l + (r-l)/2
if nums[mid] < target {
l = mid + 1
} else {
r = mid
}
}
return l
}

func lastOccurance(nums []int, target int) int {
var (
l int
r = len(nums)
)
for l != r {
mid := l + (r-l)/2
if nums[mid] <= target {
l = mid + 1
} else {
r = mid
}
}
return l
}

// double index scan
// Time complexity: O(n)
// Space complexity: O(1)
func searchRange1(nums []int, target int) []int {
var (
l int
r = len(nums) - 1
)

for l <= r {
flag := false
if nums[l] != target {
l++
flag = true
}
if nums[r] != target {
r--
flag = true
}
if !flag {
break
}
}
if r < l {
return []int{-1, -1}
}
return []int{l, r}
}

// binary search + linear scan
// Time complexity: O(logn) ~ O(n)
// Space complexity: O(1)
func searchRange2(nums []int, target int) []int {
var (
l int
r = len(nums) - 1
tmp = -1
)

for l <= r {
mid := l + (r-l)/2
if nums[mid] == target {
tmp = mid
break
}
if nums[mid] < target {
l = mid + 1
} else {
r = mid - 1
}
}
if -1 == tmp {
return []int{-1, -1}
}
l = tmp
r = tmp
for true {
if l > 0 && nums[l-1] == target {
l--
} else {
break
}
}
for true {
if r < len(nums)-1 && target == nums[r+1] {
r++
} else {
break
}
}
return []int{l, r}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package findfirstandlastpositionofelementinsortedarray

import (
"reflect"
"runtime"
"testing"
)

func TestSearchRange(t *testing.T) {
type arg struct {
nums []int
target int
}

testCases := []arg{
arg{
nums: []int{5, 7, 7, 8, 8, 10},
target: 8,
},
arg{
nums: []int{5, 7, 7, 8, 8, 10},
target: 6,
},
arg{
nums: []int{1},
target: 1,
},
arg{
nums: []int{},
target: 0,
},
arg{
nums: []int{2, 2},
target: 2,
},
arg{
nums: []int{1},
target: 0,
},
}

expected := [][]int{
{3, 4},
{-1, -1},
{0, 0},
{-1, -1},
{0, 1},
{-1, -1},
}

testFuncs := []func([]int, int) []int{
searchRange,
searchRange1,
searchRange2,
}

for _, testFunc := range testFuncs {
for index, testData := range testCases {
if res := testFunc(testData.nums, testData.target); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("function %s, expected %v, got %v", runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name(), expected[index], res)
}
}
}
}
1 change: 1 addition & 0 deletions src/README.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
|0020|[Valid Parentheses](0020_valid_parentheses/valid_parentheses.go)|Easy|*`string;`* *`stack`*|
|0021|[Merge Two Sorted Lists](0021_merge_two_sorted_lists/mergeTwoLists.go)|Easy|*`linked list`*|
|0025|[Reverse Nodes in k-Group](./0025_reverse_nodes_in_k_group/reverse_node_k_group.go)|Hard|*`linked list`*|
|0034|[ Find First and Last Position of Element in Sorted Array](0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go)|Medium|*`binary search`*|
|0061|[Rotate List](./0061_rotate_list/rotate_list.go)|Medium|*`linked list`*|
|0062|[Unique Paths](./0062_unique_paths/unique_paths.go)|Medium|*`recursion;`* *`memory search;`* *`dynamic programming`*|
|0063|[Unique Paths 2](./0063_unique_paths_2/unique_paths2.go)|Medium|*`recursion;`* *`memory search;`* *`dynamic programming`*|
Expand Down
4 changes: 2 additions & 2 deletions utils/set.go
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ func (s Set) Size() int {
}

// Clear 清空集合
func (s Set) Clear() {
s = make(Set)
func (s *Set) Clear() {
*s = make(Set)
}

// Equal 判断两个set是否相等
Expand Down
69 changes: 69 additions & 0 deletions utils/set_test.go
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package utils

import (
"testing"
"unsafe"
)

func TestEmptyStruct(t *testing.T) {
if unsafe.Sizeof(Exists) != 0 {
t.Error("Exists size must be zero.")
}
}

func TestContains(t *testing.T) {
set := NewSet(3, 4)
set.Add(5)
if set.Contains(3) != true {
t.Error("should contains 4.")
}

if set.Contains(6) != false {
t.Error("should not contains 6.")
}
}

func TestSize(t *testing.T) {
set := NewSet(3, 4)
set.Add(5)
if set.Size() != 3 {
t.Error("size should be 3.")
}
}

func TestEqual(t *testing.T) {
set := NewSet(3, 4)
set.Add(5)

set1 := NewSet(3, 4, 5)
if set.Equal(set1) != true {
t.Error("set should equal with set1.")
}
set1.Add(6)
if set.Equal(set1) == true {
t.Error("set shouldn't equal with set1.")
}
}

func TestIsSubset(t *testing.T) {
set := NewSet(3, 4)
set.Add(5)

set1 := NewSet(3, 4, 5, 6)

if set1.IsSubset(set) == true {
t.Error("set1 shouldn't be set's subset.")
}

if set.IsSubset(set1) == false {
t.Error("set should be set1's subset.")
}
}

func TestClear(t *testing.T) {
set := NewSet(3, 4)
set.Clear()
if set.Size() != 0 {
t.Error("set should be clear.")
}
}

AltStyle によって変換されたページ (->オリジナル) /