Skip to content

Commit

Permalink
achieve minOfArray
Browse files Browse the repository at this point in the history
  • Loading branch information
CaiFengGH authored Aug 30, 2017
1 parent 9a475ac commit b1d5b03
Showing 1 changed file with 83 additions and 0 deletions.
83 changes: 83 additions & 0 deletions CodingInterview/33-把数组排成最小的数.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
>题目描述
一个整数数组,寻找出排列后最小的数字;

- 实现方法

基于快速排序的思想,但是排序时的比较规则发生变化;

m和n,若mn < nm,则m < n,否则n < m;

因为mn和nm容易发生大数问题,故借助字符串进行比较;

```
/**
* @author Ethan
* @desc 将整数数组排列出最小的值
*/
public class MinOfArray {
/**
* @desc 找到整数数组的排列最小值
* @param arr 整数数组
*/
public void minOfArray(int[] arr){
quickSort(arr,0,arr.length - 1);
for(int i : arr){
System.out.print(i);
}
}
/**
* @desc 基于快排思想进行排序
* 比较规则:整数m和n,mn < nm,则m < n,否则n < m;
* @param arr 数组
* @param i 左边界
* @param j 右边界
*/
private void quickSort(int[] arr, int left, int right) {
if(left < right){
int i = left;
int j = right;
int key = arr[i];
while(i < j){
//从右向左寻找首个小于关键值的值
while(i < j && isSmall(key,arr[j])){
j--;
}
//交换
if(i < j){
arr[i++] = arr[j];
}
//从左往右寻找首个大于关键值的值
while(i < j && isSmall(arr[i],key)){
i++;
}
//交换
if(i < j){
arr[j--] = arr[i];
}
}
arr[i] = key;
quickSort(arr,left,i - 1);
quickSort(arr,i + 1,right);
}
}
/**
* @desc 快排的比较规则
*/
private boolean isSmall(int i, int j) {
String m = String.valueOf(i);
String n = String.valueOf(j);
String mn = m + n;
String nm = n + m;
for(int k = 0; k < mn.length(); k++){
if(mn.charAt(k) < nm.charAt(k)){
return true;
}else if(mn.charAt(k) > nm.charAt(k)){
return false;
}
}
return true;
}
}
```

0 comments on commit b1d5b03

Please sign in to comment.