zoukankan      html  css  js  c++  java
  • 刪除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();
    }
    
  • 相关阅读:
    人生本来就是一种修行
    Go的一些趣味题库
    PHP系统常被挂马的代码
    PHP加密字符串函数(解密)
    photoshop
    截图
    用手机作为摄像头
    IM 学习记录
    编译 学习过程
    过程流水记录-编译Lua srlua使用iup-完结
  • 原文地址:https://www.cnblogs.com/aoximin/p/12550255.html
Copyright © 2011-2022 走看看