劍指 Offer 21. 調整陣列順序使奇數位於偶數前面
阿新 • • 發佈:2020-12-22
劍指 Offer 21. 調整陣列順序使奇數位於偶數前面
地址:劍指 Offer 21. 調整陣列順序使奇數位於偶數前面
問題描述:
輸入一個整數陣列,實現一個函式來調整該陣列中數字的順序,使得所有奇數位於陣列的前半部分,所有偶數位於陣列的後半部分。
示例:
輸入:nums = [1,2,3,4]
輸出:[1,3,2,4]
注:[3,1,2,4] 也是正確的答案之一。提示:
1 <= nums.length <= 50000
1 <= nums[i] <= 10000
//快排思想應用 object Solution { def exchange(nums: Array[Int]): Array[Int] = { var (left, right) = (0, nums.length-1) while (left < right) { //left += 1 while(left < right && (nums(left)&1) == 1){ left += 1 } //right -= 1 while(left < right && (nums(right)&1) == 0){ right -= 1 } if (left < right) { val temp = nums(left) nums(left) = nums(right) nums(right) = temp } println("left: " + left) println("right: " + right) } return nums } }
//快慢指標方法 import "fmt" func exchange(nums []int) []int { fast ,slow := 0, 0 for fast < len(nums) { if (nums[fast] & 1) == 1 { temp := nums[fast] nums[fast] = nums[slow] nums[slow] = temp slow += 1 } //fast += 1 //fmt.Println("-------------------") //fmt.Printf("fast: %d\n", fast) //fmt.Printf("slow: %d\n", slow) //fmt.Println(nums) fast += 1 } return nums }