_ _Given an array of ints, for example [6, 4, -3, 0, 5, -2, -1, 0, 1, -9]
, implement in one of the following languages
to move all positive integers to the left, all negative integers to the right, and all zeros to the middle.
You are not allowed to consume extra O(n) storage space, aka. your algorithm space complexity should be O(1).
Your answer should be compilable and runnable, in one of the following function signatures:
func SplitNumbers(numbers []int) []int {
//posIndex :=0
// 先查找+
slow := 0
for numbers[slow]>0{
slow++ // 找到第一个非正数的位置
}
fast :=slow+1//
for fast<len(numbers){
if numbers[fast]>0 {
numbers[slow],numbers[fast] = numbers[fast],numbers[slow]
slow =slow+1
for numbers[slow]>0{
slow++ // 找到非正数的位置
}
if slow>fast {
fast=slow+1
}
}else {
fast++
}
}
for numbers[slow]==0{
slow++ // 找到第一个非正数的位置
}
fast =slow+1
for fast<len(numbers){
if numbers[fast]==0 {
numbers[slow],numbers[fast] = numbers[fast],numbers[slow]
}
for numbers[slow]==0{
slow++ // 找到第一个非正数的位置
}
fast++
}
return numbers
}
func main() {
fmt.Println(CloudmallInterview2([]int{6, 4, -3, 0, 5, -2, -1, 0, 1, -9}))
fmt.Println(CloudmallInterview2([]int{-6, -4, -3, 0, 5, 2, 1, 0, 1, 9}))
}
前后两个指针
func SplitNumbers(numbers []int) []int {
//posIndex :=0
// 先查找+
left := 0
right :=len(numbers)-1
for left<right{
for numbers[right]<=0{
right--
}
if numbers[left]<=0 {
numbers[left],numbers[right]= numbers[right],numbers[left]
}
left++
}
right =len(numbers)-1
for left<right{
for left<right&&numbers[right]!=0{
right--
}
if numbers[left]<0 {
numbers[left],numbers[right]= numbers[right],numbers[left]
}
left++
}
return numbers
}
func main() {
fmt.Println(CloudmallInterview2([]int{6, 4, -3, 0, 5, -2, -1, 0, 1, -9}))
fmt.Println(CloudmallInterview2([]int{-6, -4, -3, 0, 5, 2, 1, 0, 1, 9}))
}