• 剑指offer-把数组排成最小的数,第一个只出现一次的字符


    把数组排成最小的数

    描述:

    输入一个正整数数组,把所有的数字拼接起来排成一个数字。打印最小的那个。

    思路:

    定义一个排序规则,两两比较。mn和nm哪个更小。用字符串存储拼接的字符串。

    代码:

    bool cmp(string a, string b)
    {
    	string temp1 = a + b;
    	//cout << temp1 << endl;
    	
    	string temp2 = b + a;
    	//cout << temp2 << endl;
    	return temp1 <temp2;
    
    }
    void  SortArrforMinNumber(int arr[],int len)
    {
    	vector<string> s;
    	for (int i = 0; i < len; i++)
    	{
    		s.push_back(to_string(arr[i]));
    
    	}
    	sort(s.begin(),s.end(),cmp);
    	for (int i = 0; i < len; i++)
    	{
    		cout << s[i];
    	}
    
    }
    

    第一个只出现一次的字符

    思路:

    字符大小为8bit,共256个。那么可以用哈希表存储字符的次数。第一次遍历数组,将次数存储到哈希表中,第二次遍历数组找到哈希表中次数为一的字符。

    代码:

    //PS 在字符串1中删除字符串2中出现过的字符  也可以用哈希表 
    //PS 删除字符串中重复的字符  用bool哈希表
    //变位词  出现的字母和次数相同。一个哈希表 ,+1 -1操作,
    char FindFirstNotRepeatChar(char* str)
    {
    	if (str == NULL)
    	{
    		return '';
    	}
    	const int tablesize = 256;
    	int hashtable[256];
    	for (int i = 0; i < tablesize; i++)
    	{
    		hashtable[i] = 0;
    	}
    	char* p = str;
    	while (*p != '')
    	{
    		hashtable[int(*p)]++;
    		p++;
    	}
    	p = str;
    	while (*p != '')
    	{
    		if (hashtable[int(*p)] == 1)
    			return *p;
    		p++;
    	}
    	return '';
    
    }
    
  • 相关阅读:
    [hdu2196]Computer树的直径
    [poj2342]Anniversary party树形dp入门
    链式前向星模板
    LintCode-50.数组剔除元素后的乘积
    Markdown的基本语法
    LintCode-8.旋转字符串
    LintCode-1.A + B 问题
    LintCode-61.搜索区间
    LintCode-88.最近公共祖先
    LintCode-54.转换字符串到整数
  • 原文地址:https://www.cnblogs.com/void-lambda/p/12411533.html
Copyright © 2020-2023  润新知