刪除k个数字后的最小值

前言

比如说 1593212,去掉一个数字后,保留的是最小值。

原理:因为要保留最小值,那么要删除最高位的数字是最明显的。

那么1和5到底删除哪一个呢?当然是删除最大值了。

代码

public static int AfterdeleteKeys(int init,int keys)
{
	string temp = init.ToString();
	if (temp.Length <= keys)
	{
		return 0;
	}
	var hasdel = false;
	for (; keys > 0;)
	{
		hasdel = false;
		for (int i = 0; i < temp.Length-1; i++)
		{
			if (temp[i]>=temp[i+1])
			{
				hasdel = true;
				temp = temp.Substring(0, i) + temp.Substring(i+1,temp.Length-i-1);
				keys--;
				break;
			}
		}
		if (!hasdel)
		{
			break;
		}
	}
   temp= temp.Substring(0,temp.Length-keys);
	return Convert.ToInt32(temp);
}

static void Main(string[] args)
{
	Console.WriteLine(AfterdeleteKeys(123467,1));
	Console.ReadKey();
}

上面效率并不高。
优化,将char[] 物理结构转换为 stack 逻辑逻辑。

public static int AfterdeleteKeys(int init, int keys)
{
	var temp = init.ToString();
	if (keys >= temp.Length)
	{
		return 0;
	}
	char[] stack = new char[temp.Length - keys];
	var top = 0;
	for (int i = 0; i < temp.Length; i++)
	{
		char c=temp[i];
		if (top > 0 && stack[top - i] > c && keys > 0)
		{
			top--;
			keys--;
		}
		if (top < stack.Length)
		{
			stack[top] = c;
			top++;
		}
		else
		{
			break;
		}
	}
	var offset = 0;
	while (offset < stack.Length && stack[offset] == '0')
	{
		offset++;
	}
	return offset == stack.Length ? 0 :Convert.ToInt32(new String(stack,offset,stack.Length-offset));
}


static void Main(string[] args)
{
	Console.WriteLine(AfterdeleteKeys(123467,1));
	Console.ReadKey();
}

猜你喜欢

转载自www.cnblogs.com/aoximin/p/12550255.html