Created
December 15, 2017 18:51
-
-
Save jianminchen/50416b7186d88b23fdadcb928fd6c374 to your computer and use it in GitHub Desktop.
Array value equal index - June 8 practice, two issues, first time complexity is O(n), not O(logn); And the smallest index is not found. Edge case is handled properly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Solution | |
{ | |
static int indexEqualsValueSearch(int[] arr) | |
{ | |
// your code goes here | |
if(arr == null || arr.Length == 0) | |
{ | |
return -1; | |
} | |
int length = arr.Length; | |
for(int i = 0; i < length; i++) | |
{ | |
arr[i] = arr[i] - i; | |
} | |
// binary search 0 on arr | |
var index = BinarySearch(arr, 0, length); | |
return index; | |
} | |
// -8, -1, 0, 3, start = 0, end = 3 | |
// 100, 0, end = 0 | |
public static int BinarySearch(int[] numbers, int start, int end) | |
{ | |
if( start > end) | |
{ | |
return -1; | |
} | |
while(start <= end) // 0 <= 3; 2 <=3 | |
{ | |
int middle = start + ( end - start) / 2; // 1, 2 | |
int value = numbers[middle]; // -1, 0 | |
bool isSearchValue = value == 0; // true | |
if(isSearchValue) | |
{ | |
return middle; // 2 | |
} | |
else if( value > 0 ) | |
{ | |
end = middle - 1; // -1 | |
} | |
else | |
{ | |
start = middle + 1; // 2 | |
} | |
} | |
return -1; | |
} | |
static void Main(string[] args) | |
{ | |
var testcase = new int[]{-8, 0, 2,5}; | |
Console.WriteLine(indexEqualsValueSearch(testcase)); | |
var testcase2 = new int[]{-8, 1, 2,5}; | |
Console.WriteLine("second case is "+ indexEqualsValueSearch(testcase2)); | |
} | |
} | |
// -8, 0, 2, 5 -> sorted array, assuming ascending order, gap element >= 1 | |
// distinct integers | |
// 0, 1, 2, 3 -> sorted array, gap = 1 | |
// gap element >=1 - 1 => gap >= 0 | |
// -8, -1, 0, 2 <-- see if there is an element which has value zero | |
// -8, 0, 2, 3, 5 | |
// 0, 1, 2, 3, 4 | |
// two elements = | |
// return first one -> O(n) -> O(logn) | |
// use the same array taken away index value, and then binary search the array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment