Created
August 10, 2020 12:55
-
-
Save RaheelYawar/233224f27eaf1bc2b0a27272d7502c60 to your computer and use it in GitHub Desktop.
Given an array of integers sorted in descending order and in the range 1 through n, write some code to find the index of the first instance of a specific number and the total number of instances that are in the array.
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; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var ans = GetIndexAndCount(new int[] {10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 4, 3, 3, 3, 3}, 9); | |
Console.Write(ans[0] + " " + ans[1]); | |
} | |
public static int[] GetIndexAndCount(int[] nums, int target) { | |
if (nums.Length == 0) { return new int[] {-1, -1}; } | |
int start = 0, end = nums.Length - 1, mid = 0; | |
while (start <= end) { | |
mid = start + (end - start) / 2; | |
if (nums[mid] == target) { | |
return GetIndexAndCountUtil(mid, nums, target); | |
} else if (nums[mid] > target) { | |
start = mid + 1; | |
} else { | |
end = mid - 1; | |
} | |
}// end of while | |
return new int[] {-1, -1}; | |
} | |
public static int[] GetIndexAndCountUtil(int index, int[] nums, int target) { | |
int start = index, end = index; | |
bool update = true; | |
while (update) { | |
update = false; | |
if (start > 0 && nums[start - 1] == target) { | |
start--; | |
update = true; | |
} | |
if (end < nums.Length - 1 && nums[end + 1] == target) { | |
end++; | |
update = true; | |
} | |
}// end of while | |
return new int[] {start, (end - start) + 1}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment