【劍指offer】21 調整數組順序使得奇數位於偶數之前(第一次遇到限制時間的題)

面試題21. 調整數組順序使奇數位於偶數前面

難度簡單16

輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有奇數位於數組的前半部分,所有偶數位於數組的後半部分。

 

示例:

輸入:nums = [1,2,3,4]
輸出:[1,3,2,4] 
注:[3,1,2,4] 也是正確的答案之一。

 

提示:

  1. 1 <= nums.length <= 50000
  2. 1 <= nums[i] <= 10000

第一次解題思路,list存儲(時間超限),但是樣例全部過

class Solution {
    public int[] exchange(int[] nums) {
        LinkedList<Integer> list = new LinkedList<>();
        LinkedList<Integer> list1 = new LinkedList<>();
        for(int i = 0;i<nums.length;i++){
            if(nums[i] % 2 == 0)
                list1.add(nums[i]);
            else 
                list.add(nums[i]);
        }
        list.addAll(list1);
        int [] array = new int[list.size()];
        for(int i = 0;i<list.size();i++){
            array[i] = list.get(i);
        }
        return array;
    }
}

後來,嗯,就是後來,快慢指針

class Solution {
    public int[] exchange(int[] nums) {
        int low = 0;
        int high = nums.length-1;
        while(low< high){
            if(low<high && nums[low] % 2!=0) low++;
            if(low<high && nums[high] % 2==0) high--;
            int temp = nums[low];
            nums[low] = nums[high];
            nums[high] = temp;
        }
        return nums;
    }
}

 

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