【刷题打卡】day3-双指针

从现在开始每天至少刷一道题。
题库:lintcode

有些题目链接打不开,需要权限,那大家就去九章算法参考答案里找找。

539. Move Zeroes

题目链接
难度:easy
算法:同向双指针

解题思路
同向双指针指的是两个指针从头走到尾,方向相同。一看到这种把0放到一头,非0的数字放另一头的题目,而且还是in-place,优先考虑用双指针。双指针特别是同向双指针的题目最主要是理解两根指针代表的含义。这道题我们需要一根指针(right)遍历原来的数组,还要一根指针(left)指示新数组非0元素的位置。在遍历原数组中,如果元素非0, 那么就把这个元素替换到非0元素的位置。如果原数组遍历完,left指针还没指向数组尾端,那么剩下位置的元素都是0。

时间复杂度:O(N)
空间复杂度:O(1)

解法

public class Solution {
    /**
     * @param nums: an integer array
     * @return: nothing
     */
    public void moveZeroes(int[] nums) {
        // write your code here

        int left = 0; // none-zero position for new array
        int right = 0; // for old array
        
        while(right < nums.length){
            if(nums[right] != 0){
                nums[left] = nums[right];
                left++;
            }
            right++;
        }
        
        //if left doesn't reach the end of nums, change the remaining to be 0
        while(left < nums.length){
            nums[left] = 0;
            left++;
        }
        

    }
}

609. Two Sum - Less than or equal to target

题目链接
难度:medium
算法:相向双指针

解题思路
相向双指针指两个指针一头一尾,相向靠近。相向双指针使用前提数组有序
一看two sum的题目,用相向双指针秒做。先将数组排序,然后用双指针。当两个元素的和小于等于target时,如果右指针继续往左移,两个元素和依旧小于等于target。因此,可以直接把右指针和左指针中间的数加到答案里, 然后移动左指针。

时间复杂度:O(NlogN), 因为排序要花O(NlogN), 使用双指针O(N)
空间复杂度:O(1)

解法

public class Solution {
    /**
     * @param nums: an array of integer
     * @param target: an integer
     * @return: an integer
     */
    public int twoSum5(int[] nums, int target) {
        // write your code here
        Arrays.sort(nums);
        
        int left = 0;
        int right = nums.length - 1;
        int ans = 0;
        
        while(left < right){
            if(nums[left] + nums[right] <= target){
                ans = ans + right - left;
                left++;
            }else{
                right--;
            }
            
        }
        
        return ans;
        
    }
}

还有几道变形题,大家不用做,瞅瞅就行,思路基本一致
608. Two Sum II - Input array is sorted
533. Two Sum - Closest to target
443. Two Sum - Greater than target

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值