LeetCode 之双指针 two pointers

2023-11-01 15:48

本文主要是介绍LeetCode 之双指针 two pointers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},A solution set is:(-1, 0, 1)(-1, -1, 2)
two pointer scan

遍历数组,双指针维护一个区间进行加和比较。

vector<vector<int> > threeSum(vector<int> &num) {vector<vector<int>> result;sort(num.begin(),num.end());for(int i=0; i<num.size(); i++){int target = 0-num[i];int start = i+1;int end = num.size()-1;while(start<end){if(num[start]+ num[end] == target){vector<int> solution;solution.push_back(num[i]);solution.push_back(num[start]);solution.push_back(num[end]);result.push_back(solution);start++, end--;while(start<end && num[start] == num[start-1]) start++;while(start<end && num[end] == num[end+1]) end--;}else if(num[start] + num[end] >target)end--;elsestart++;}while(i<num.size() && num[i] == num[i+1]) i++;}return result;
}
其中18,19行 去除前后的重复 比如[-2,-2,-2,0,2,3,4,4,4]

26行去除遍历时的重复 比如[2,2,3,3,5]

2. 3Sum Closet

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

与3Sum 类似,需要加一个记录最小距离的变量

int threeSumClosest(vector<int> &num, int target) {int result;vector<int> solution;sort(num.begin(), num.end());int minD = INT_MAX;for(int i=0; i<num.size()-2;i++){int start = i+1;int end = num.size()-1;while(start < end){int sum = num[i]+num[start]+num[end];if(sum == target){minD = 0;result = sum;return result;}else if(sum<target){if(target-sum < minD){minD = target-sum;result = sum;}start++;}else{if(sum-target < minD){minD = sum-target;result = sum;}end--;}}while(i<num.size() && num[i] == num[i+1]) i++;}return result;
}

3. 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.A solution set is:(-1,  0, 0, 1)(-2, -1, 1, 2)(-2,  0, 0, 2)

上述问题其实可以归纳为K sum问题,解题思路都比较相似。

都是要求, N个数字中,找出k个数字之和 == target (去重复)

解法:

排序,头尾两指针扫描找到相应的求和

3sum 可以化成 2sum, 4sum 可以化成3sum

比如:

排好序后数字为a b c d e f g h

先枚举a, 然后再b--h中查询

再枚举b 在c-h中查询

以此类推

这里有一篇博文总结的很好,来自烟客旅人

http://tech-wonderland.net/blog/summary-of-ksum-problems.html


vector<vector<int> > fourSum(vector<int> &num, int target) {vector<vector<int>> result;sort(num.begin(), num.end());for(int i=0; i<num.size();i++){int target1 = target- num[i];for(int j=i+1; j<num.size();j++){int target2 = target1-num[j];int start = j+1;int end = num.size()-1;while(start<end){if(num[start]+num[end]==target2){vector<int> solution;solution.push_back(num[i]);solution.push_back(num[j]);solution.push_back(num[start]);solution.push_back(num[end]);result.push_back(solution);start++, end--;while(start<end && num[start] == num[start-1]) start++;while(start<end && num[end] == num[end+1]) end--;}else if(num[start] + num[end] >target2)end--;elsestart++;}while(j<num.size() && num[j] == num[j+1]) j++;}while(i<num.size() && num[i] == num[i+1]) i++;}return result;
}

4.Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

实现题, 双指针操作,

string addBinary(string a, string b) {string result;reverse(a.begin(),a.end());reverse(b.begin(),b.end());int maxL = a.size()>b.size() ? a.size() : b.size();int carry = 0;for(int i=0; i<maxL; i++){int la = i<a.size()? a[i]-'0':0;int lb = i<b.size()? b[i]-'0':0;int sum = (la+lb+carry)%2;carry = (la+lb+carry)/2;result.insert(result.begin(),sum+'0');}if(carry == 1)result.insert(result.begin(),'1');return result;
}

5. Add two numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


和 add binary 类似,指针操作不同

v1

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {int carry = 0;ListNode *result = new ListNode(-1);ListNode *head = result;ListNode *p1 = l1;ListNode *p2 = l2;while(p1!=NULL && p2!=NULL){int sum = (p1->val+p2->val+carry)%10;carry = (p1->val+p2->val+carry)/10;ListNode *didgt = new ListNode(sum);head->next = didgt;head = head->next;p1 = p1->next, p2 = p2->next;}while(p1!=NULL){int sum = (p1->val+carry)%10;carry = (p1->val+carry)/10;ListNode *didgt = new ListNode(sum);head->next = didgt;head = head->next;p1 = p1->next;}while(p2!=NULL){int sum = (p2->val+carry)%10;carry = (p2->val+carry)/10;ListNode *didgt = new ListNode(sum);head->next = didgt;head = head->next;p2 = p2->next;}if(carry!=0){ListNode *didgt = new ListNode(carry);head->next = didgt;}return result->next;
}


v2

ListNode *addTwoNumbersS2(ListNode *l1, ListNode *l2) {int carry = 0;ListNode *result = new ListNode(-1);ListNode *head = result;ListNode *p1 = l1;ListNode *p2 = l2;while(p1!=NULL || p2!=NULL){int av = p1 !=NULL? p1->val :0;int bv = p2 !=NULL? p2->val :0;int sum = (av+bv+carry)%10;carry = (av+bv+carry)/10;ListNode *didgt = new ListNode(sum);head->next = didgt;head = head->next;p1 = p1 !=NULL? p1->next:NULL;p2 = p2 !=NULL? p2->next:NULL;}if(carry!=0){ListNode *didgt = new ListNode(carry);head->next = didgt;}head = result->next;delete result;return head;
}

6.Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

int removeElement(int A[], int n, int elem) {int cur =0;for(int i=0;i<n;i++){if(A[i]==elem)continue;A[cur] = A[i];cur++;}return cur;
}



未完待续

这篇关于LeetCode 之双指针 two pointers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/324050

相关文章

Java空指针异常NullPointerException的原因与解决方案

《Java空指针异常NullPointerException的原因与解决方案》在Java开发中,NullPointerException(空指针异常)是最常见的运行时异常之一,通常发生在程序尝试访问或... 目录一、空指针异常产生的原因1. 变量未初始化2. 对象引用被显式置为null3. 方法返回null

go 指针接收者和值接收者的区别小结

《go指针接收者和值接收者的区别小结》在Go语言中,值接收者和指针接收者是方法定义中的两种接收者类型,本文主要介绍了go指针接收者和值接收者的区别小结,文中通过示例代码介绍的非常详细,需要的朋友们下... 目录go 指针接收者和值接收者的区别易错点辨析go 指针接收者和值接收者的区别指针接收者和值接收者的

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

解决java.lang.NullPointerException问题(空指针异常)

《解决java.lang.NullPointerException问题(空指针异常)》本文详细介绍了Java中的NullPointerException异常及其常见原因,包括对象引用为null、数组元... 目录Java.lang.NullPointerException(空指针异常)NullPointer

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return