@@ -54,4 +54,53 @@ public int findMinSolutionTwo(int[] nums) {
54
54
// Java expects a value to be returned even if conditions inside while-loop fails
55
55
return 0 ;
56
56
}
57
+
58
+ // SOLUTION 3
59
+ public int findMinSolutionThree (int [] nums ) {
60
+
61
+ /*
62
+ * Time Complexity: O(log n) where n = length of nums. Nums is split by half until one element remains.
63
+ * Then, the algorithm compares that one element in its half.
64
+ *
65
+ * Space Complexity: O(1) because no dynamic data structure or stack was created.
66
+ */
67
+
68
+ if (nums .length == 1 ) {
69
+ return nums [0 ];
70
+ }
71
+
72
+ // Create a return variable. This will hold the smallest element
73
+ int res = nums [0 ];
74
+
75
+ // Create a left and right pointer
76
+ int leftPtr = 0 ;
77
+ int rightPtr = nums .length - 1 ;
78
+
79
+ // Iterate array
80
+ while (leftPtr <= rightPtr ) {
81
+
82
+ // If the array between left and right pointer is already sorted in ascending order, return the smallest value
83
+ if (nums [leftPtr ] < nums [rightPtr ]) {
84
+ res = Math .min (res , nums [leftPtr ]);
85
+ break ;
86
+ }
87
+
88
+ // Calculate middle index
89
+ int midIdx = (int ) rightPtr - leftPtr / 2 ;
90
+ res = Math .min (res , nums [midIdx ]);
91
+
92
+ // If left half of subarray is already sorted in ascending order, then move leftPtr to the right half to investigate the right side.
93
+ // E.g., [3, 4, 5, 1, 2]
94
+ if (nums [midIdx ] >= nums [leftPtr ]) {
95
+ leftPtr = midIdx + 1 ;
96
+ }
97
+ else {
98
+ // If right half of subarray is already sorted in ascending order, then move rightPtr to the left left half.
99
+ // E.g., [1, 2, 3, 4, 5]
100
+ rightPtr = midIdx - 1 ;
101
+ }
102
+ }
103
+
104
+ return res ;
105
+ }
57
106
}
0 commit comments