Topic describes

Take an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half.

Example:

Input: nums = [1,2,3,4] output: [1,3,2,4] note: [3,1,2,4] is also one of the correct answers.

Tip:

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

Source: LeetCode link: leetcode-cn.com/problems/di… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Method a

The easiest thing to think of

func exchange(_ nums: [Int])- > [Int] {
    var temp: [Int] = []
    nums.forEach {
        if $0 & 1 = = 1 {
            temp.insert($0, at: 0)}else {
            temp.append($0)}}return temp
}
Copy the code

Complete only basic solutions, using only beginner programmers. Aspiring programmers should think of funnier solutions.

Solution two: differential double pointer

A better source to eat with this GIF

func exchange1(_ nums: [Int])- > [Int] {
    var fastP: Int = 0
    var slowP: Int = 0
    var temp = nums

    while fastP < nums.count {
        if temp[fastP] & 1 = = 1 {
            temp.swapAt(fastP, slowP)
            slowP + = 1
        }
        fastP + = 1
    }

    return temp
}
Copy the code

👋

  • 📦 Archive technical documentation
  • 🐙 making
  • Wechat: RyukieW

My apps

Minesweeper Elic Endless Ladder Dream of books
type The game financial
AppStore Elic Umemi