-
Notifications
You must be signed in to change notification settings - Fork 0
/
searching_for_items_in_an_array.go
124 lines (105 loc) · 2.54 KB
/
searching_for_items_in_an_array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package fun_with_arrays
// checkIfExist Problem: Check If N and Its Double Exist
//
// LeetCode: https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3250/
//
// Hint 1:
// Loop from i = 0 to arr.length, maintaining in a hashTable the array elements from [0, i - 1].
// Hint 2:
// On each step of the loop check if we have seen the element 2 * arr[i] so far or arr[i] / 2 was seen if arr[i] % 2 == 0.
func checkIfExist(arr []int) bool {
if len(arr) == 0 {
return false
}
if len(arr) == 1 {
return false
}
values := map[int]int{}
for i := 0; i < len(arr); i++ {
values[arr[i]] = i
}
for i := 0; i < len(arr); i++ {
current := arr[i]
if current == 0 {
if j, ok := values[current]; ok {
if j == i {
continue
}
return true
}
}
if j, ok := values[current/2]; ok && current%2 == 0 {
if j == i {
continue
}
return true
}
if j, ok := values[2*current]; ok {
if j == i {
continue
}
return true
}
}
return false
}
// validMountainArray Problem: Valid Mountain Array.
//
// LeetCode: https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
//
// Hint 1:
// It's very easy to keep track of a monotonically increasing or decreasing ordering of elements.
// You just need to be able to determine the start of the valley in the mountain and from that point onwards,
// it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array
// and you will be able to come up with a straightforward solution.
func validMountainArray(arr []int) bool {
if len(arr) == 1 {
return false
}
if len(arr) == 2 {
return false
}
valleyLeft := arr[0]
valleyRight := arr[len(arr)-1]
peak := -1
hasPlato := false // We don't know mountain has plato at start.
decreasingFound := false // We don't know direction on start.
for i := 1; i < len(arr); i++ {
// Find top of the hill.
if arr[i] > peak {
peak = arr[i]
}
// Plato found...
if arr[i] == arr[i-1] {
hasPlato = true
}
// Going up the hill.
if arr[i] > arr[i-1] {
// After plato has been found
// we should not increase.
if hasPlato {
return false
}
// If we goes down, we can't go
// up anymore.
if decreasingFound {
return false
}
}
// Going down the hill.
if arr[i] < arr[i-1] {
// decreasing
decreasingFound = true
if hasPlato {
return false
}
}
}
if valleyRight >= peak {
return false
}
if valleyLeft >= peak {
return false
}
return true
}