題目來源:華為模擬題
題目描述
華為模擬測試題,蠻簡單,一個長度為n的整型數組,亂序存放0至n-1,要求只能交換0和其中的一個數,對數組進行排序(也沒有說升序還是降序),交換的函數他已經寫好了。給出如下結構:
public class Solution {
public void swapWithZero(int[] array, int len, int n) {
Main.SwapWithZero(array, len, n);
}
public void sort(int[] array, int len) {
// 完成這個函數
}
}
要求完成這個sort函數,在sort函數中調用
swapWithZero函數進行排序,注意這里的n是指要調換的數,並不是在數組中的下標!
分析
首先需要始終明確幾點:
- 數組為[0, n-1],是連續的,只是亂序的。
- 從始至終只能交換0和其中某個數。
- 不需要考慮怎么交換
- 最終排好的數組,下標和該位置上的數相同,這點非常重要
基本思想:
- 首先將0放到第一位上,還有1->n-1的位置上需要排序
- 循環n-1次,每次將一個數放到相應的位置上。這里就要用到數組的特點,第1次循環(0已經在下標為0的位置上了)將1放到下標為1的位置上,第2次循環將2放到下標為2的位置上,……,第n-1次循環,將n-1放在n-1的位置上!
下面來看一下我采用的示例{4,5,0,3,1,2}
首先看一下手工推導過程

這里只是將1交換到相應位置處的過程! - 第一步將0和初始數組第一個數交換,將0交換到第一位。
- 第二步將0和1交換,將1交換到第一個位置上。
- 第三步將當前正在處理(循環處)的位置下標處(位置1)的數和0交換(有點繞)。
- 第四步將1和0交換,這樣1就到了應該呆的位置上了。同時0又回到了第一個,方便下次操作!
實現(java 1.8)
package sxtest20190409;
/**
* @ClassName: Solution
* @Author: fanjiajia
* @Date: 2019/4/9 下午8:12
* @Version: 1.0
* @Description:
*/
public class Solution {
public static void main(String[] args) {
int[] array = {4,5,0,3,2,1};
Solution solution = new Solution();
solution.sort(array, array.length);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public void sort(int[] array, int len) {
// 完成這個函數
// 將0移動到第一位
int firstNum = array[0];
swapWithZero(array, len, firstNum);
// 還有位置1->n-1位置的數需要移動
for (int index = 1; index < len; index++) {
//每次循環將index處放置該位置應該的數(index本身)
swapWithZero(array,len, index); // 將index 放在首位
int indexNum = array[index];
swapWithZero(array, len, indexNum);
swapWithZero(array, len, index);
}
}
public void swapWithZero(int[] array, int len, int n) {
Main.SwapWithZero(array, len, n);
}
}
class Main {
/**
* 交換數組中0和n
* @param array
* @param len
* @param n
*/
public static void SwapWithZero(int[] array, int len, int n) {
/**
* 1 0的位置更改為n
* 2 n的位置改為0
*/
for (int i = 0; i < len; i++) {
if (array[i] == 0) {
array[i] = n;
}
else if (array[i] == n) {
array[i] = 0;
}
}
}
}
這里自定義實現了Main類,以及其中的SwapWithZero函數,這里交換相對簡單,直接賦值即可。
最后
此致,敬禮
