Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created September 20, 2016 17:48
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/a865fd512e176ecf973338036db563c7 to your computer and use it in GitHub Desktop.
Save jianminchen/a865fd512e176ecf973338036db563c7 to your computer and use it in GitHub Desktop.
HackerRank - kth zero - remove hashset, still time out on last 2 test cases
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KthZero
{
class Program
{
/*
* Sept. 20, 2016
* Try to fix time out issues
*/
static void Main(string[] args)
{
string[] arr = Console.ReadLine().Split(' ');
int queries = Convert.ToInt32(arr[1]);
string[] table = Console.ReadLine().Split(' ');
int[] arrZero = toZeroArray(table);
Array.Sort(arrZero);
for (int i = 0; i < queries; i++)
{
string[] arr2 = Console.ReadLine().Split(' ');
int symbol = Convert.ToInt32(arr2[0]);
int kth = Convert.ToInt32(arr2[1]);
if (symbol == 1)
{
Console.WriteLine(getKthZero(
table,
arrZero,
kth));
}
else if (symbol == 2)
{
updateQuery(
table,
ref arrZero,
arr2);
}
}
}
/*
* return an array with index value of zero elements
*/
private static int[] toZeroArray(string[] table)
{
int len = table.Length;
IList<int> res = new List<int>();
for (int i = 0; i < len; i++)
{
int val = Convert.ToInt32(table[i]);
if (val == 0)
res.Add(i);
}
return res.ToArray();
}
private static string getKthZero(
string[] table,
int[] zeroArray,
int kth)
{
string NO = "NO";
if (kth >= 1 &&
kth <= zeroArray.Length
)
return zeroArray[kth - 1].ToString();
else
return NO;
}
private static void updateQuery(
string[] table,
ref int[] arr,
string[] para
)
{
int kth = Convert.ToInt32(para[1]);
int newValue = Convert.ToInt32(para[2]);
if (kth < 0 || kth > table.Length)
return;
int index = Array.BinarySearch(arr, kth);
bool isIn = index >= 0;
if (isIn && newValue != 0)
arr = removeOne(
arr,
kth);
else if (!isIn && newValue == 0)
arr = addOne(
arr,
kth
);
table[kth] = newValue.ToString();
}
private static int[] removeOne(
int[] arr,
int kth)
{
int len = arr.Length;
int[] arr1 = new int[len - 1];
int count = 0;
for (int i = 0; i < arr.Length; i++)
{
int val = arr[i];
if (val != kth)
arr1[count++] = val;
}
return arr1;
}
private static int[] addOne(
int[] arr,
int kth)
{
int len = arr.Length;
int[] arr1 = new int[len + 1];
int count = 0;
bool addNew = false;
for (int i = 0; i < len; i++)
{
int val = arr[i];
if (val < kth)
arr1[count++] = val;
else if (val > kth && !addNew)
{
addNew = true;
arr1[count++] = kth;
arr1[count++] = arr[i];
}
else if (val > kth && addNew)
arr1[count++] = arr[i];
}
// edge case
if (!addNew)
{
arr1[count] = kth;
}
return arr1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment