1
+ package medium
2
+
3
+ import ArraysTopic
4
+ import BinarySearchTopic
5
+
6
+ /* *
7
+ * 81. Search in Rotated Sorted Array II
8
+ * https://leetcode.com/problems/search-in-rotated-sorted-array/
9
+ *
10
+ There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
11
+ Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length)
12
+ such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
13
+ For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].
14
+ Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
15
+ You must decrease the overall operation steps as much as possible.
16
+ BULLSHIT
17
+ */
18
+
19
+ class Medium81 : BinarySearchTopic , ArraysTopic {
20
+
21
+ fun search (nums : IntArray , target : Int ): Boolean {
22
+ val n = nums.size
23
+ if (n == 0 ) return false
24
+ var end = n - 1
25
+ var start = 0
26
+ while (start <= end) {
27
+ val mid = start + (end - start) / 2
28
+ if (nums[mid] == target) {
29
+ return true
30
+ }
31
+ if (! isBinarySearchHelpful(nums, start, nums[mid])) {
32
+ start++
33
+ continue
34
+ }
35
+ // which array does pivot belong to.
36
+ val pivotArray = existsInFirst(nums, start, nums[mid])
37
+
38
+ // which array does target belong to.
39
+ val targetArray = existsInFirst(nums, start, target)
40
+ if (pivotArray xor targetArray) { // If pivot and target exist in different sorted arrays, recall that xor is true when both operands are distinct
41
+ if (pivotArray) {
42
+ start = mid + 1 // pivot in the first, target in the second
43
+ } else {
44
+ end = mid - 1 // target in the first, pivot in the second
45
+ }
46
+ } else { // If pivot and target exist in same sorted array
47
+ if (nums[mid] < target) {
48
+ start = mid + 1
49
+ } else {
50
+ end = mid - 1
51
+ }
52
+ }
53
+ }
54
+ return false
55
+ }
56
+
57
+ // returns true if we can reduce the search space in current binary search space
58
+ private fun isBinarySearchHelpful (arr : IntArray , start : Int , element : Int ): Boolean {
59
+ return arr[start] != element
60
+ }
61
+
62
+ // returns true if element exists in first array, false if it exists in second
63
+ private fun existsInFirst (arr : IntArray , start : Int , element : Int ): Boolean {
64
+ return arr[start] <= element
65
+ }
66
+ }
67
+
68
+ fun main () {
69
+ println (Medium81 ().search(intArrayOf(2 , 5 , 6 , 0 , 0 , 1 , 2 ), 0 ))
70
+ println (Medium81 ().search(intArrayOf(2 , 5 , 6 , 0 , 0 , 1 , 2 ), 3 ))
71
+ println (Medium81 ().search(intArrayOf(1 , 0 , 1 , 1 , 1 ), 0 ))
72
+ }
0 commit comments