LeetCode: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 

函数原型:
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    }
};

解题思路:

1、暴力法:两个for循环遍历,时间复杂度为O(N^2),会超时。

2、排序法:这里有两种思路:

  1)排好序后,利用区间法来计算两个数的和(两个指针分别指向首尾,逐步向中间收缩)

  2)排好序后,固定一个元素a[i],在余下的数中查找target - a[i],查找可用二分查找法,时间复杂度为O(lgn)。

该种方法的时间复杂度为O(nlgn)。

注意:这种方法由于采用了排序,故每个数的index会改变,所以,必须将每个数和它的index进行关联,我们第一时间想到map,但是map不允许有重复的元素出现,故不合适。进而可以想到结构体,每个数有两个属性:value和index,这样就搞定了。

3、hashtable法:时间复杂度降为O(N)。思想来自排序法的第一种思路,这种方法用到了查找,总所周知,查找最快的方法就是采用hash表。但是前面也说过,hash不能存储重复的元素,比如(0,3,2,0),只存储3个元素,那查找后就无法得到正确答案。这个时候就需要想一种方法来避免这种情况,我们可以这样来做:来一个元素a[i],我们检查它是否在hash表中,不在就插入,然后检查target-a[i]是否在表中,如果在,得到结果。这样就可以得到我们想要的结果,千万不要把所有元素都插入了,再来查找,不然就得不到答案。

代码展示:

排序法:(第一种思路)

 1 //方法一:排序法
 2 struct SNode {
 3     int value;
 4     int pos;
 5 };
 6
 7 bool cmp(SNode a, SNode b)
 8 {
 9     return a.value < b.value;
10 }
11
12 vector<int> twoSum(vector<int>& nums, int target) {
13     int n = nums.size();
14
15     vector<int> vecRet;
16     vector<SNode> vecNode;
17
18     for (int i=0; i < n; i ++) {
19         SNode temp;
20         temp.value = nums[i];
21         temp.pos = i+1;
22         vecNode.push_back(temp);
23     }
24     sort(vecNode.begin(),vecNode.end(), cmp);
25
26     int i = 0, j = n-1;
27     while(i < j) {
28         int sum = vecNode[i].value + vecNode[j].value;
29         if (sum == target) {
30             if(vecNode[i].pos < vecNode[j].pos){
31                 vecRet.push_back(vecNode[i].pos);
32                 vecRet.push_back(vecNode[j].pos);
33                 break;
34             }
35             if (vecNode[i].pos > vecNode[j].pos) {
36                 vecRet.push_back(vecNode[j].pos);
37                 vecRet.push_back(vecNode[i].pos);
38                 break;
39             }
40         }
41         else if (sum > target)
42             j--;
43         else
44             i ++;
45     }
46     return vecRet;
47 }

hashtable法:

 1 //方法二:hashtable法
 2 vector<int> twoSum1(vector<int>& nums, int target)
 3 {
 4     int i, sum;
 5     vector<int> results;
 6     map<int, int> hmap;
 7     for(i=0; i<nums.size(); i++){
 8         if(!hmap.count(nums[i])){
 9             hmap.insert(pair<int, int>(nums[i], i));
10         }
11         if(hmap.count(target-nums[i])){
12             int j=hmap[target-nums[i]];
13             if(j<i){
14                 results.push_back(j+1);
15                 results.push_back(i+1);
16                 return results;
17             }
18         }
19     }
20     return results;
21 }
时间: 2024-08-30 00:04:06

LeetCode:Two_Sum的相关文章

leetcode two_sum (easy) /java

刷题背景 担心找不到工作. 看think in java略枯燥,传智播客的视频太浅显. 于是刷题练习算法和java. 废话少说. 题: java菜鸟一枚,用自己的编译器便于检查语法错误. 所以首先写了一个main函数,用于测试. 1 public static void main(String[] args) 2 { 3 Scanner input=new Scanner(System.in); 4 String s=input.nextLine(); 5 String[] s1=s.split

[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 018.4Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/4sum/ 代码(github):https://github.com/illuz/leetcode 题意: 给一个数列 S ,找出四个数 a,b,c,d 使得a + b + c + d = targ

[LeetCode] 001. Two Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 001.Two_Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/two-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 一个数组中两个位置上的数的和恰为 target,求这两个位置. 分析: 暴力找

[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)

全部最新的题解可以在 我的 github 上找,欢迎 star 和 watch ~ 更新中~~ 说明 这个系列的题解包括用 C++/Java/Python 写的 leetcode 上的算法题目,和 Sql 写的 leetcode 上的数据库题目. 有些题目虽然 AC 了却还没写分析,所以这次就开坑来完成. 链接: 我的 github Leetcode Algorithms Problems Leetcode Database Problems CSDN 题解索引 001.Two_Sum (Med

Leetcode算法系列(链表)之两数相加

Leetcode算法系列(链表)之两数相加 难度:中等给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字.如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和.您可以假设除了数字 0 之外,这两个数都不会以 0 开头.示例:输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)输出:7 -> 0 -> 8原因:342 + 465 = 807 链接:https://le

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,

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 OJ - Longest Consecutive Sequence

这道题中要求时间复杂度为O(n),首先我们可以知道的是,如果先对数组排序再计算其最长连续序列的时间复杂度是O(nlogn),所以不能用排序的方法.我一开始想是不是应该用动态规划来解,发现其并不符合动态规划的特征.最后采用类似于LRU_Cache中出现的数据结构(集快速查询和顺序遍历两大优点于一身)来解决问题.具体来说其数据结构是HashMap<Integer,LNode>,key是数组中的元素,所有连续的元素可以通过LNode的next指针相连起来. 总体思路是,顺序遍历输入的数组元素,对每个