剑指offer:把数组排成最小的数

本文介绍了一种通过快速排序算法将数组中的数字重新排列的方法,目的是得到这些数字所能组成的最小数值。通过定义特殊的字符串比较规则,确保了组合出的数字最小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入一个正整数数组,把数组里的所有数字拼接起来排成一个数,打印能拼接出的所有数字中的最小的一个。例如输入数组{3,32,321},则打印出这3个数字能排成的最小数字321323

package com.interview;

import java.util.Scanner;

/*
 * 数组排列中寻找最小排列的数,把数组排列成最小的数
 *
 */
public class ArrayMin {
	public int partition(String[] str, int low, int high) {
		int i = low, j = high;
		String tmp = str[low];
		while (i < j) {
			while (i < j && compare(str[j], tmp) >= 0)
				j--;
			if (i < j && compare(str[j], tmp) < 0)
				str[i] = str[j];
			while (i < j && compare(str[i], tmp) <= 0)
				i++;
			if (i < j && compare(str[i], tmp) > 0)
				str[j] = str[i];
		}
		str[i] = tmp;
		return i;
	}

	public void quickSort(String[] str, int low, int high) {
		if (low < high) {
			int mid = partition(str, low, high);
			quickSort(str, low, mid - 1);
			quickSort(str, mid + 1, high);
		}
	}

	//compare函数是比较两个字符串大小的函数,规则如下
	//例如,"123">"12321","123"<"12345"
	public int compare(String s1, String s2) {
		int i = 0;
		int min = s1.length() < s2.length() ? s1.length() : s2.length();
		while (i < min) {
			if (s1.charAt(i) < s2.charAt(i))
				return -1;
			if (s1.charAt(i) > s2.charAt(i))
				return 1;
			if (s1.charAt(i) == s2.charAt(i))
				i++;
		}
		if (s1.length() == s2.length())
			return 0;
		else if (s1.length() < s2.length())
			return s1.compareTo(s2.substring(min));
		else
			return (s1.substring(min)).compareTo(s2);
	}

	public static void main(String[] args) {
		int n;
		ArrayMin am = new ArrayMin();
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入数组长度:\n");
		n = sc.nextInt();
		int[] A = new int[n];
		String[] str = new String[n];
		System.out.println("请输入数组元素:\n");
		for (int i = 0; i < n; ++i) {
			A[i] = sc.nextInt();
			str[i] = String.valueOf(A[i]);
		}
		am.quickSort(str, 0, str.length - 1);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length; ++i) {
			// System.out.println(str[i]);
			sb.append(str[i]);
		}
		System.out.println("\n" + sb.toString());
	}
}


我们的排列原则就是对于一个数字数组,例如是{3,32,321}

现在我们比较32与321,我们先比较第1位,'3'=='3',再比较第2位,'2'=='2',此时32已经结束,于是我们重新用32来与321中剩下的1做比较。知道比较除了结果为止。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值