第539题
描述
给一个数组 nums 写一个函数将 0
移动到数组的最后面,非零元素保持原数组的顺序
注意:1.必须在原数组上操作
2.最小化操作数
样例
例1:
输入: nums = [0, 1, 0, 3, 12],
输出: [1, 3, 12, 0, 0].
例2:
输入: nums = [0, 0, 0, 3, 1],
输出: [3, 1, 0, 0, 0].
代码如下:
public class Solution {
/**
* @param nums: an integer array
* @return: nothing
*/
public void moveZeroes(int[] nums) {
// write your code here
int n=nums.length;
int i=0;
for(int j=0;j<n;j++)//采用直接交换
{
if(nums[j]!=0)
{
swap(nums,i,j);
i++;
}
}
}
void swap(int[] nums,int beforeIndex,int afterIndex)
{
int temp=nums[beforeIndex];
nums[beforeIndex]=nums[afterIndex];
nums[afterIndex]=temp;
}
}
第767题
描述
原地意味着你不能使用额外空间
样例 1:
输入 : nums = [1,2,5]
输出 : [5,2,1]
代码如下:
public class Solution {
/**
* @param nums: a integer array
* @return: nothing
*/
public void reverseArray(int[] nums) {
// write your code here
int n=nums.length;
for(int i=0;i<n/2;i++)
{
swap(nums,i,n-i-1);
}
}
void swap(int[] nums,int beforeIndex,int afterIndex)
{
int temp=nums[beforeIndex];
nums[beforeIndex]=nums[afterIndex];
nums[afterIndex]=temp;
}
}