题目1:
给定一个整数数组,将数组中元素 0 挪动到开端并放弃非 0 元素的程序
结题思路:
使用双指针,顺次遍历,将非 0 元素向前移,而后将对应地位的数字设置为 0.
代码
go
func moveZeroes(nums []int){ lens := len(nums) if lens == 0 { return } index := 0 for i := 0; i < lens; i++ { if nums[i] != 0 { nums[index] = nums[i] index++ } } if index < lens { for { nums[index] = 0 index++ if index == lens { break } } }}
php
function test($arr):array { $len = count($arr); if ($len < 1) { return []; } $index = 0; for ($i=0; $i < $len; $i++) { if ($arr[$i] != 0) { $arr[$index] = $arr[$i]; $index++; } } while($index < $len) { $arr[$index++] = 0; } return $arr;}
题目2:
给定两个整数数组 nums1 和 nums2,返回它们的交加数组。
解题思路:
先将2个数组排序,而后一个数组对应一个指针,顺次比对两个数组的值,相等则独特指针前移,不相等时,则数字小的那个数组指针前移,直到任意一个数组指针移到开端为止。
代码
go
func intersect(nums1 ,nums2 []int) []int { sort.Ints(nums1) sort.Ints(nums2) res := make([]int, 0) lena,lenb := len(nums1),len(nums2) left,right := 0,0 for { if (left == lena || right == lenb) { break; } if nums1[left] < nums2[right] { left++ } else if nums1[left] == nums2[right] { res = append(res, nums1[left]) left++ right++ } else { right++ } } return res}
php
function test($a, $b):array { $lena = count($a); $lenb = count($b); $res = []; sort($a); sort($b); $left = $right = 0; while($left < $lena && $right < $lenb) { if ($a[$left] < $b[$right]) { $left++; } elseif ($a[$left] == $b[$right]) { $res[] = $a[$left]; $left++; $right++; } else { $right++; } } return $res;}