【算法題】要求對數組中的元素進行重新排列,負數放到前面,不改變相對順序

import java.util.Scanner;

/**
 * 
題目描述 給定一個未排序的整數數組,數組中的元素有正數也有負數,要求對數組中的元素進行重新排列,
使得負數排在正數的前面,並且不改變原來正數和負數之間的相對順序。例如,如果輸入是{1,7,-5,9,-12,15},
則輸出是{-5,-12,1,7,9,15}。要求時間複雜度爲O(n),空間複雜度爲O(1)
思路描述 由於不改變相對順序,可以參考之前字符串中字符移動的代碼,具體實現如下:

 * @author changfu1
 *
 */
public class Learn1 {

    public static void swap(int[] num, int i, int j) {
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
    
    /** * 這種算法的空間複雜度O(1) ,但是時間複雜度爲O(n) */
    public static void main(String[] args) { // TODO Auto-generated method stub
        Scanner scaneer = new Scanner(System.in);
        while(scaneer.hasNextInt()) {
            int n = scaneer.nextInt();
            int[] num = new int[n];
            for(int i = 0; i  < n; i++) {
                num[i] = scaneer.nextInt();
            }
            /**
             * num1用來標記當前處理到第幾個數
             */
            int temp = 0;
            int num1 = 0;
            int i = 0;
            while( i < n && num1 <n) {
                if(num[i] < 0 ) {
                    ++i;++num1;
                    continue;
                }else{
                    temp = num[i];
                    for(int j = i; j < n-1; j ++ ) {
                        num[j] = num[j+1];
                        num[n-1] = temp; 
                    }
                    //arr[i]爲正數的時候,後面的數會前移,這是arr[i]變爲arr[i+1],爲了不漏掉數,所以i不能變。--一次和++一次保證i不變
                    //但是這有可能會導致死循環。所以用num來標記已處理數的個數。
                    i--;
                }
                
                ++i;
                ++num1;
            }
            
            for (int k : num) {
                System.out.println(k);
            }
        }
        
        /*Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int num[] = new int[n];
            for (int i = 0; i < n; i++) {
                num[i] = scanner.nextInt();
            }
            int i = 0;
            int j = 0;
            int pos = 0;
            while (i <= n - 1) {
                if (num[i] < 0) {
                    swap(num, i, j);
                    pos = j;
                    while (pos < i) {
                        ++pos;
                        swap(num, i, pos);
                    }
                    ++j;
                }
                ++i;
            }
            for (i = 0; i < n; i++) {
                System.out.print(num[i] + " ");
            }
            System.out.println();
        }*/
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章