双指针
题目一
283.移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
解题思路
因为要求不允许创建格外的数组去存值,所以我们依然是运用两个变量去控制原数组的下标,在一个For循环内,同时将0个个数计算出来,并且将不为0的数前移。
class Solution {
public void moveZeroes(int[] nums) {
int i=0;int j=0;
int count=0;
for(i=0;i<nums.length;i++)
{
if(nums[i]==0)
{
count++;
}
else
{
nums[j]=nums[i];
j++;
}
}
for(i=0;i<count;i++)
{
nums[nums.length-1-i]=0;
}
}
}
题目二
- 两数之和 II - 输入有序数组
给定一个已按照 非递减顺序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
解题思路
在之前的两数之和中,我们运用到了HashMap,现在我们使用双指针去实现。因为数组本身就是已经排好序的,所以我们仅需判断前面的与后面的相加是否大于目标数即可。大于则说明最后一个数大了,右指针往前,小了说明左指针指的数小了,左指针加即可。
class Solution {
public int[] twoSum(int[] numbers, int target) {
int j=numbers.length-1;
for(int i=0;i<j;)
{
int addnum=numbers[i]+numbers[j];
if(addnum==target)
{
return new int []{i+1,j+1};
}
else if(addnum>target) j--;
else if(addnum<target)i++;
}
return null;
}
}