[LeetCode] Largest Number

简介: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

解题思路:先按照一定的规则对数字进行排序,排序规则是:对两个变量从最高位开始进行逐位比较,当只有其中一个变量还有未比较位数时,从该位数字开始,与另一变量进行逐位比较。当该变量只有一位时,则看该位是否不小于另一变量中的最大数字。

实现代码:

/*****************************************************************************
    *  @COPYRIGHT NOTICE
    *  @Copyright (c) 2015, 楚兴
    *  @All rights reserved
    *  @Version  : 1.0

    *  @Author   : 楚兴
    *  @Date     : 2015/2/6 13:23
    *  @Status   : Accepted
    *  @Runtime  : 9 ms
*****************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
	string largestNumber(vector<int> &num) {
		Solution s;
		string str = "";
		sort(num.begin(),num.end(),s);
		char ch[11];
		int sum = 0;
		for (auto it = num.begin(); it != num.end(); it++)
		{
			sum += *it;
			itoa(*it,ch,10);
			str += ch;
		}
		return sum == 0 ? "0" : str;
	}

	bool operator()(int m, int n)
	{
		if (m == n)
		{
			return false;
		}
		char ch1[11];
		char ch2[12];
		itoa(m,ch1,10);
		itoa(n,ch2,10);
		char* t1 = ch1;
		char* t2 = ch2;
		while (*t1 && *t2)
		{
			if (*t1 != *t2)
			{
				return *t1 > *t2;
			}
			t1++;
			t2++;
		}
		while (*t1)
		{
			return strcmp(t1,ch2);
		}
		while(*t2)
		{
			return !strcmp(t2,ch1);
		}
	}
private:
	char maxchar(char* ch)
	{
		char* temp = ch;
		char max = '\0';
		while(*temp)
		{
			max = max > *temp ? max : *temp;
			temp++;
		}
		return max;
	}
    //如果ch1应在前,返回true,否则返回false
	bool strcmp(char* ch1, char* ch2)
	{
		char* t1 = ch1;
		char* t2 = ch2; // ch2位数较短
		while (*t1)
		{
			if (*t2 == '\0')
			{
				t2 = ch2; //指向首字符
			}
			if (*t1 != *t2)
			{
				return *t1 > *t2; 
			}
			else
			{
				if (*(t1 + 1) == '\0')
				{
					char c = maxchar(ch2);
					bool b = *t1 >= c;
					return b;
				}
			}
			t1++;
			t2++;
		}
		return false;
	}

	void itoa(int n, char ch[11], int R = 10)
	{
		char* temp = ch;
		if (n == 0)
		{
			strcpy(ch,"0");
			return;
		}
		while(n)
		{
			*temp++ = n % R + '0';
			n = n / R;
		}
		*temp = '\0';
		reverse(ch);
	}

	void reverse(char ch[11])
	{
		char* p = ch;
		char* q = ch + strlen(ch) - 1;
		char c;
		while(p < q)
		{
			c = *p;
			*p++ = *q;
			*q-- = c;
		}
	}
};
int main()
{
	vector<int> nums;
	nums.push_back(8308);
	nums.push_back(830);
	for (int i = 9; i >= 0; i--)
	{
		nums.push_back(i);
	}
	nums.push_back(2281);
	nums.push_back(121);
	nums.push_back(12);

	Solution s;
	string str = s.largestNumber(nums);
	cout<<str.c_str()<<endl;
	system("pause");
}
第二种思路:省去前面找排序思路的复杂过程,直接先排序,再检验。
/*****************************************************************************
    *  @COPYRIGHT NOTICE
    *  @Copyright (c) 2015, 楚兴
    *  @All rights reserved
    *  @Version  : 2.0

    *  @Author   : 楚兴
    *  @Date     : 2015/2/6 14:06
    *  @Status   : Accepted
    *  @Runtime  : 12 ms
*****************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
	string largestNumber(vector<int> &num) {
		Solution s;
		string str = "";
		sort(num.begin(),num.end(),s);
		char ch[11];
		int sum = 0;
		for (auto it = num.begin(); it != num.end(); it++)
		{
			sum += *it;
			itoa(*it,ch,10);
			str += ch;
		}
		return sum == 0 ? "0" : str;
	}

	bool operator()(int m, int n)
	{
		if (m == 0) //等于0时不能放前面
		{
			return false;
		}
		
		char ch1[11];
		char ch2[11];
		itoa(m,ch1);
		itoa(n,ch2);
		if (strlen(ch1) == strlen(ch2))
		{
			return m >= n;
		}
		
		char ch3[22];
		char ch4[22];
		memcpy(ch3,ch1,sizeof(ch1));
		strcat(ch3,ch2);
		memcpy(ch4,ch2,sizeof(ch2));
		strcat(ch4,ch1);

		char* t1 = ch3;
		char* t2 = ch4;
		while(*t1)
		{
			if (*t1 != *t2)
			{
				return *t1 > *t2;
			}
			t1++;
			t2++;
		}
		return true;
	}
private:
	void strcat(char* input, char* output)
	{
		char* t1 = input;
		char* t2 = output;
		while (*t1)
		{
			t1++;
		}
		while(*t2)
		{
			*t1++ = *t2++;
		}
		*t1 = '\0';
	}

	void itoa(int n, char ch[11], int R = 10)
	{
		char* temp = ch;
		if (n == 0)
		{
			strcpy(ch,"0");
			return;
		}
		while(n)
		{
			*temp++ = n % R + '0';
			n = n / R;
		}
		*temp = '\0';
		reverse(ch);
	}

	void reverse(char ch[11])
	{
		char* p = ch;
		char* q = ch + strlen(ch) - 1;
		char c;
		while(p < q)
		{
			c = *p;
			*p++ = *q;
			*q-- = c;
		}
	}
};
int main()
{
	vector<int> nums;
	nums.push_back(8308);
	nums.push_back(830);
	for (int i = 9; i >= 0; i--)
	{
	nums.push_back(0);
	}
	nums.push_back(2281);
	nums.push_back(121);
	nums.push_back(12);

	Solution s;
	string str = s.largestNumber(nums);
	cout<<str.c_str()<<endl;
	char ch[10];
	memset(ch,0,2);
	cout<<strlen(ch)<<endl;
	system("pause");
}


Java代码:

// Runtime: 129 ms
public class Solution {
    public String largestNumber(int[] nums) {
        String[] words = new String[nums.length];
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            words[i] = String.valueOf(nums[i]);
        }
        if (sum == 0) {
            return "0";
        }
        
        Arrays.sort(words, new Comparator<String>() {
                public int compare(String o1, String o2) {
                    String s1 = o1 + o2;
                    String s2 = o2 + o1;
                    return s2.compareTo(s1);
                }
            }
        );
        StringBuilder sb = new StringBuilder();
        for (String word : words) {
            sb.append(word);
        }
        return sb.toString();
    }
}


目录
相关文章
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
103 1
|
6月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
7月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
48 0
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
39 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
|
3月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
4月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
119 2