Created
December 15, 2017 06:36
-
-
Save jianminchen/00d9fdbc67754616a0206ce30f9f0503 to your computer and use it in GitHub Desktop.
Array distinct element - find value equal the index of element using binary search, need to remove diff extra array, so time complexity can lower to O(logn) instead of O(n).
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 | |
{ | |
public static int IndexEqualsValueSearch(int[] arr) // [0, 1, 2, 3] | |
{ | |
if(arr == null || arr.Length == 0) // false | |
{ | |
return -1; | |
} | |
var length = arr.Length; // 4 | |
var diff = new int[length]; // O(n) | |
for(int i = 0; i < length; i++) // bottom - O(n) | |
{ | |
diff[i] = arr[i] - i; // 0 | |
} | |
return binarySearch(diff,0, 0, length - 1); // 0, 0 , 3 | |
} | |
private static int binarySearch(int[] numbers, int search, int start, int end) // logn - | |
{ | |
if(start > end) // false | |
{ | |
return -1; | |
} | |
var middle = start + (end - start)/2; // 1 | |
var middleValue = numbers[middle]; // 0 | |
// base case | |
if(middleValue == search) // | |
{ | |
// You need to make some changes here | |
// You definitely know 1 index | |
// [0 0 0 0 0] | |
// middle = 2 | |
// [0 0] | |
if(middle > 0 && numbers[middle - 1] == 0) | |
{ | |
return binarySearch(numbers, search, start, middle - 1); | |
} | |
else | |
{ | |
return middle; // 1 -> lowest one - bug fix | |
} | |
} | |
else if( middleValue < search) | |
{ | |
start = middle + 1; | |
} | |
else | |
{ | |
end = middle - 1; | |
} | |
return binarySearch(numbers, search, start, end); | |
} | |
static void Main(string[] args) | |
{ | |
} | |
} | |
// [-8, 0, 2, 5] - distinct ascending -> increment at least 1 | |
// [0, 1, 2, 3] -> ascending order -> increment 1 | |
// arr[i] - i -> array not descending | |
// arr[i] <= arr[i] if i < j | |
// [0, 1, 2, 3] | |
// newArray = arr[i] - i , saying that this array is sorted, | |
// [0,0,0,0] -> sorted, | |
// argument if it is sorted, binary search | |
// O(logn) given value 0, find index - arr[i] - i = 0, | |
// space O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment