Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/49b3880fedeabf30492cc87bf91b147b to your computer and use it in GitHub Desktop.
Save jianminchen/49b3880fedeabf30492cc87bf91b147b to your computer and use it in GitHub Desktop.
Leetcode 33 - search sorted rotated array - use short names
using System;
/// <summary>
/// Leetcode 33 - Search number in sorted rotated array
/// </summary>
class Solution
{
public static int ShiftedArrSearch(int[] shiftArr, int num)
{
if (shiftArr == null || shiftArr.Length == 0)
{
return -1;
}
return runModifiedBinarySearch(shiftArr, num, 0, shiftArr.Length - 1);
}
/// <summary>
/// code review on Nov 24, 2017
/// Use short variable names
/// code review on Nov. 23, 2017
/// Make sure that the code is simple as possible.
/// No code smell, no copy and paste.
/// ONLY CHECK THE FIRST HALF AND SEE IF IT IS IN THE FIRST HALF.
/// </summary>
/// <param name="numbers"></param>
/// <param name="search"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
private static int runModifiedBinarySearch(int[] numbers, int search, int start, int end)
{
if (start > end)
{
return -1;
}
int middle = start + (end - start) / 2;
bool found = numbers[middle] == search;
// base case, find one solution.
if (found)
{
return middle;
}
var middleValue = numbers[middle];
var startValue = numbers[start];
var endValue = numbers[end];
var firstHalfAscending = startValue <= middleValue; // the first half can be only one node
var biggerOnes = search >= startValue;
var smallerOnes = search < middleValue;
var inFirstHalfGivenMinMax = biggerOnes && smallerOnes; // inclusive
var notInSecondHalfGivenMinMax = biggerOnes || smallerOnes; // exclusive
var firstHalfAscendingCase = firstHalfAscending && inFirstHalfGivenMinMax;
var secondHalfAscendingCase = !firstHalfAscending && notInSecondHalfGivenMinMax;
if (firstHalfAscendingCase || secondHalfAscendingCase)
{
return runModifiedBinarySearch(numbers, search, start, middle - 1);
}
else
{
return runModifiedBinarySearch(numbers, search, middle + 1, end);
}
}
static void Main(string[] args)
{
RunTestcase();
}
public static void RunTestcase()
{
ShiftedArrSearch(new int[] { 1, 3 }, 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment