[LeetCode] Two Sum系列

LeetCode 1. Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

分析:

此题是这个系列中AC率最低的一道了,楼主并没有想出什么好办法,当你没有好办法的时候,总是想到暴搜,这样不好,嘿嘿。暴搜就不用多说了,复杂度为O(n2)。以下给出一种O(n)的解法,利用unordered_map的哈希存储优势。

代码:

class Solution {
    public:
    vector<int> twoSum(vector<int>& nums, int target) {
         vector<int> results(2,-1);
         unordered_map<int,int> marks;
         int len = nums.size();
         for(int i=0; i < len; i++){
             if(marks.find(target-nums[i])!=marks.end()){
                  results[0] = marks[target-nums[i]] + 1;
                  results[1] = i + 1;
                  break;
             } else
             marks[nums[i]] = i;
         }
         return results;
    }
}   

LeetCode 167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

分析:

有序的这道题比较自然的能想到单趟快排的思想,复杂度为O(n)。在数组的两端分别设一个指针,如果两数之和大于target,则左移尾指针;小于target则右移头指针,直到遇到一对和等于target的整数。

代码:

class Solution{
public:
    vector<int> TwoSum(vector<int> nums, int target){
        vector<int> ret(2,-1);
        int begin=0;
        int end = nums.size()-1;
        while(begin<end){
             int tempSum = nums[begin]+nums[end];
             if(tempSum > target)
                  end--;
             else if(tempSum < target)
                  begin++;
             else
                  break;
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;
    }
}    

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ret={-1,-1};
        int begin=0;
        int end=nums.length-1;
        while(begin<end){
            int tempSum = nums[begin]+nums[end];
            if(tempSum>target)
                end--;
            else if(tempSum<target)
                begin++;
            else
                break;
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;
    }
}

延伸思考:

试想想这道题的变种, 如果去掉这个假设(有且仅有一对数满足要求),也就是说可能一对符合要求的都没有,也有可能有多对,要求全部输出。

时间: 2024-07-31 00:30:58

[LeetCode] Two Sum系列的相关文章

leetcode 之Sum系列(七)

第一题是Two Sum 同样是用哈希表来做,需要注意的是在查打gap是要排除本身.比如target为4,有一个值为2,gap同样为2. vector<int> twoSum(vector<int> &num, int target) { unordered_map<int, int> mapping; vector<int> result; for (int i = 0; i < num.size(); i++) mapping[num[i]]

[Leetcode] Sum 系列

Sum 系列题解 Two Sum题解 题目来源:https://leetcode.com/problems/two-sum/description/ Description Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one sol

LeetCode OJ - Sum Root to Leaf Numbers

这道题也很简单,只要把二叉树按照宽度优先的策略遍历一遍,就可以解决问题,采用递归方法越是简单. 下面是AC代码: 1 /** 2 * Sum Root to Leaf Numbers 3 * 采用递归的方法,宽度遍历 4 */ 5 int result=0; 6 public int sumNumbers(TreeNode root){ 7 8 bFSearch(root,0); 9 return result; 10 } 11 private void bFSearch(TreeNode ro

leetcode -- 3 sum

3-sum 题目描述: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 题目要求: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ 

[leetcode]Combination Sum @ Python

原题地址:https://oj.leetcode.com/problems/combination-sum/ 题意: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited

Leetcode:Path Sum 二叉树路径和

Path Sum: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return

LeetCode: Combination Sum [038]

[题目] Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target)

LeetCode: Combination Sum II [039]

[题目] Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be

LeetCode——Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 给定一个二叉树和一个值,找出所有根到叶的路径和等于