前言
今天的題目
每天的題目見github(看最新的日期):
https://github.com/gzc426
具體的題目可以去牛客網(wǎng)對(duì)應(yīng)專題去找。
題目
每天一道劍指offer-把數(shù)組排成最小的數(shù)
來源:
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
題目詳述
輸入一個(gè)正整數(shù)數(shù)組,把數(shù)組里所有數(shù)字拼接起來排成一個(gè)數(shù),打印能拼接出的所有數(shù)字中最小的一個(gè)。例如輸入數(shù)組{3,32,321},則打印出這三個(gè)數(shù)字能排成的最小數(shù)字為321323。
思路
和昨天的那道題一樣,全排列數(shù)組中所有的情況,把所有結(jié)果存到treeSet里面,然后由于是treeSet是按照從小到大排序的,所有返回第一個(gè)結(jié)果就行。
題目詳解
import java.util.*;
public class Solution {
? ?public String PrintMinNumber(int [] numbers) {
? ? ? ?if(numbers.length == 0)
? ? ? ? ? ?return "";
? ? ? ?TreeSet<String> set = new TreeSet<>();
? ? ? ?PrintMinNumber(numbers,0,set);
? ? ? ?return set.pollFirst();
? ?}
? ?public void PrintMinNumber(int [] numbers,int index,TreeSet<String> set)
? ?{
? ? ? ?if(index == numbers.length-1)
? ? ? ?{
? ? ? ? ? ?String tempStr = "";
? ? ? ? ? ?for(int i=0;i<numbers.length;i++)
? ? ? ? ? ? ? ?tempStr += String.valueOf(numbers[i]);
? ? ? ? ? ?set.add(tempStr);
? ? ? ?}else{
? ? ? ? ? ?for(int i=index;i<numbers.length;i++)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?swap(numbers,index,i);
? ? ? ? ? ? ? ?PrintMinNumber(numbers,index+1,set);
? ? ? ? ? ? ? ?swap(numbers,index,i);
? ? ? ? ? ?}
? ? ? ?}
? ?}
? ?public void swap(int [] numbers,int i,int j)
? ?{
? ? ? ?int temp = numbers[i];
? ? ? ?numbers[i] = numbers[j];
? ? ? ?numbers[j] = temp;
? ?}
}
結(jié)束語
作者喬戈里親歷2019秋招,哈工大計(jì)算機(jī)本碩,百度java工程師,歡迎大家關(guān)注我的微信公眾號(hào):程序員喬戈里,公眾號(hào)有3T編程資源,以及我和我朋友(百度C++工程師)在秋招期間整理的近200M的面試必考的java與C++面經(jīng),并有每天一道leetcode打卡群與技術(shù)交流群,歡迎關(guān)注。