lintcode(379)将数组重新排序以构造最小值

本文介绍了一种算法,用于将整数数组重新排序以构造出可能的最小值。通过自定义快速排序方法,实现了对整数的有效排序,并提供了一个示例代码实现。

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

Description:

给定一个整数数组,请将其重新排序,以构造最小值。

 注意事项

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

Explanation:

给定 [3, 32, 321],通过将数组重新排序,可构造 6 个可能性数字:

3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323

其中,最小值为 321323,所以,将数组重新排序后,该数组变为 [321, 32, 3]

Solution:

重写新的排序方法,采用快速排序的方式。比较大小、交换位置均需要重新定义。

先后面向前遍历查找小于current的值,然后从前向后查找大于current的值。

public class Solution {
    /**
     * @param nums n non-negative integer array
     * @return a string
     */
    public String minNumber(int[] nums) {
        // Write your code here
        StringBuilder result = new StringBuilder();
        quickSort(nums , 0 , nums.length - 1);
        for(int i = 0;i<nums.length;i++){
            if(result.length() == 0 && nums[i] == 0) continue;
            result.append(String.valueOf(nums[i]));
        }
        if(result.toString().length() == 0){
            return "0";
        }
        return result.toString();
    }
    
    public void quickSort(int[] nums , int start , int end){
        if(start < end){
            int current = nums[start];
            int i = start;
            int j = end;
            while(i < j){
                while(i < j && compare(nums[j] , current) >=0 ){
                    j--;
                }
                while(i < j && compare(nums[i] , current) <=0 ){
                    i++;
                }
                if(i < j){
                    swap(nums , i , j);
                }
            }
            swap(nums , start , i);
            quickSort(nums , start , i - 1);
            quickSort(nums , i + 1 ,end);
        }
        
    }
    
    public int compare(int num1 , int num2){
        String s1 = String.valueOf(num1);
        String s2 = String.valueOf(num2);
        return (s1 + s2).compareTo(s2 + s1);
    }
    
    public void swap(int[] nums , int i , int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值