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/b78ce6e0e410a19bd10178147ac8c855 to your computer and use it in GitHub Desktop.
Save jianminchen/b78ce6e0e410a19bd10178147ac8c855 to your computer and use it in GitHub Desktop.
Leetcode 581 - shortest unsorted continuous array
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode581_shortestUnsortedContinuousSubarray
{
/// <summary>
/// https://leetcode.com/contest/leetcode-weekly-contest-32/problems/shortest-unsorted-continuous-subarray/#_=_
/// </summary>
class Leetcode581_shortestUnsortedContinuousSubarray
{
static void Main(string[] args)
{
RunTestcase();
}
public static void RunTestcase()
{
int[] numbers = new int[] {1, 2, 3,4 };
FindShortestUnsortedContinuousSubarray(numbers);
}
/// <summary>
/// array's length is in range [1, 10,000].
///
/// </summary>
/// <param name="numbers"></param>
/// <returns></returns>
public static int FindShortestUnsortedContinuousSubarray(int[] numbers)
{
int length = numbers.Length;
int[] sorted = new int[length];
Array.Copy(numbers, sorted, length);
Array.Sort(sorted);
int start = 0;
bool foundStart = false;
for (int i = 0; i < length; i++)
{
var current = sorted[i];
var compare = numbers[i];
if (current == compare)
{
continue;
}
else
{
start = i;
foundStart = true;
break;
}
}
if (!foundStart)
{
return 0;
}
int end = length - 1;
for (int i = length - 1; i >= start; i--)
{
var current = sorted[i];
var compare = numbers[i];
if (current == compare)
{
continue;
}
else
{
end = i;
break;
}
}
return end - start + 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment