前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法学习--双指针

算法学习--双指针

作者头像
艳龙
发布2021-12-16 17:53:42
2490
发布2021-12-16 17:53:42
举报
文章被收录于专栏:yanlongli_艳龙yanlongli_艳龙

双指针分类

  • 快慢指针
  • 左右指针

快慢指针:主要解决链表相关问题,比如:典型的判断链表中是否包含环、链表倒是第K个节点等 左右指针:主要解决数组(或者字符串)中的问题:比如:二分查找

快慢指针

题目: 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。 例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点

代码语言:javascript
复制
ListNode* getKthFromEnd(ListNode* head, int k) {
        

        ListNode* later = head;
        ListNode* first = head;

        for (int i = 0; i < k; i++) {
            if (first == NULL) {
                return NULL;
            }
            first = first->next;
        }

        while(first) {
            later = later->next;
            first = first->next;
        }

        return later;
    }

左右指针

题目:给定一个按照升序排列的有序整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标 tips: 无序的数组求和,可以使用map来做

代码语言:javascript
复制
vector<int> twoSum(vector<int>& nums, int target) {

        vector<int> res;
        
        int left = 0; 
        int right = nums.size() - 1;
        int sum = -1;
        while (left < right) {
            sum = nums[left] + nums[right];
            if (sum == target) {
                res.push_back(left);
                res.push_back(right);
                return res;
            } else if (sum > target) {
                right --;
            } else if (sum < target) {
                left ++;
            }
        }
        return res;
    }

题目:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标

代码语言:javascript
复制
 public int[] twoSum(int[] nums, int target) {

        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int currentFirst = nums[i];
            int needSecond = target - currentFirst;
            int nextIndex = -1;
            if (map.containsKey(needSecond)) {
                nextIndex = map.get(needSecond);
            }
            if (nextIndex >=0) {
                return new int[]{i, nextIndex};
            }
            map.put(currentFirst, i);
        }

        throw new IllegalArgumentException("No two sum solution");
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/5/11 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 双指针分类
  • 快慢指针
  • 左右指针
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档