Sword Finger Offer Interview Question 45: Arrange the array into the smallest number

At first I thought this question was a permutation and combination question, but later I discovered that the smallest number is the number with the smallest value in the corresponding position.

That is, if you compare the splicing order of two strings, and then sort them, you can get the element that must be behind or in front of the given string if the numbers are spliced.

Then the final sort result is the final minimum value.

 

This question can’t use permutation and combination, because when comparing, the sum of each element will be much larger than the upper limit of int. If the comparison of String is implemented, the length will be inconsistent and it is difficult to compare, even if the string bit is implemented In terms of value, it would be a tedious job, not suitable for interviews.

Details to pay attention to

String splicing with StringBuilder, toString

There are also the implementation details of fast sorting. Don't get wrong

Answer code

public String minNumber(int[] nums) {
        String[] nums_s = new String[nums.length];
        for(int count=0;count<nums.length;count++){
            nums_s[count] = nums[count] + "";
        }
        qSort(nums_s,0,nums.length-1);
        StringBuilder res = new StringBuilder();
        for(int count = 0;count<nums_s.length;count++){
            res.append(nums_s[count]);
        }

        return res.toString();
    }

    public void qSort(String[] nums_s,int start,int end){
        if(start <end){
            int mid = Partitiion(nums_s,start,end);
            qSort(nums_s,start,mid-1);
            qSort(nums_s,mid+1,end);
        }
    }

    public int Partitiion(String[] nums_s,int start,int end){
        int key = start;
        int i = start;
        int j = end;
        while(i<j){
            while(i<j&&(nums_s[key] + nums_s[j]).compareTo(nums_s[j] + nums_s[key])<=0){
                j--;
            }

            while(i<j&&(nums_s[key] + nums_s[i]).compareTo(nums_s[i] + nums_s[key])>=0){
                i++;
            }

            swap(i,j,nums_s);
            
        }
        

        swap(key,j,nums_s);
        return j;
    }

    public void swap(int a,int b,String[] nums){
        String temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/114553787