forked from CaiFengGH/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
``` |