Home  >  Article  >  Backend Development  >  Reverse array in Golang without changing negative number positions

Reverse array in Golang without changing negative number positions

WBOY
WBOYforward
2024-02-08 21:51:19720browse

在 Golang 中反转数组而不改变负数位置

php Editor Baicao Reversing an array without changing the position of negative numbers is a common problem in Golang. When dealing with array reversal, a simple and straightforward method is usually used, which is to use two pointers to point to the head and tail of the array, and then swap their values ​​until the two pointers meet. However, if there are negative numbers in the array, we may need to keep their positions unchanged. To solve this problem, we can use two auxiliary arrays, one to store positive numbers and another to store negative numbers. Then, we reverse the two arrays separately and finally merge them. This allows you to reverse the entire array without changing the position of the negative numbers. This method is simple and effective and can be easily implemented in Golang.

Question content

I want to reverse the array without changing the negative positions. Below is the program I tried, I'm missing some simple logic here. Any help would be greatly appreciated.

package main
 import "fmt"
 func swapContents1(listObj []int) {
   i, j := 0, len(listObj)-1
    for i < j {
    if listObj[i] < 0 {
         i++
    }
    if listObj[j] < 0 {
        j--
    }
    listObj[i], listObj[j] = listObj[j], listObj[i]
    i++
    j--
   }
 }

func main() {

  listObj := []int{1, 2, 3, -4, 5, -6, -7}

  swapContents1(listObj)

  fmt.Println(listObj)
}

Expected output: [5 3 2 -4 1 -6 -7]

The output I get: [-6 5 3 -4 2 1 -7]

Solution

You are pretty close, you just need to check if the number is negative Add continue after the condition. So your swapContents1 function will look like this:

func swapContents1(listObj []int) {
    i, j := 0, len(listObj)-1
    for i < j {
        if listObj[i] < 0 {
            i++
            continue
        }
        if listObj[j] < 0 {
            j--
            continue
        }
        listObj[i], listObj[j] = listObj[j], listObj[i]
        i++
        j--
    }
}

The above is the detailed content of Reverse array in Golang without changing negative number positions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete