一起刷LeetCode1-Two Sum

  感觉有必要重新刷刷题了,为以后找工作做做准备,选择LeetCode+topcoder上的Data Science Tutorials,

争取每天晚上10:00开始刷一道,复习一下相关知识点。

-------------------------------------------------------分割线啦-----------------------------------------------------------------------

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

【题意】:这题意思就是给定一些数,再给你一个目标数字,让你在给定的那些数字中找出两个数,这两个数的和等于目标数字。注意给定的这些数字是无序的。

【心路历程】:看到这题,简单想了想,就知道O(n*2)的遍历一定会超时。于是进一步的思考,感觉特别像hash,可是懒得实现hash。。。

就开始想想还有没有别的方法。感觉这种无序的数字,排序后都会比较好处理一点。就开始往排序上想,发现排好序后确实比较好处理。

我们用两个下标,一个指向开始beg,一个指向末尾end,我们去比较target减去beg指向的数字,与end指向的数字。如果target-beg == end ,就找到了;

如果 target-beg > end ,就beg++;如果target-beg < end ,就end--。这样的话,时间复杂度是O(n*logn)。我感觉差不多可以接受,就交了,ac。

为了学习知识,ac不是目的,我看了一下官方解法:

O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x.

As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

- -,最佳答案就是Hash,O(n)。

---------------------------------------------------------又是分割线啦----------------------------------------------------------------------

附上代码:

(1)这个是O(n*logn)的排序+首尾下标:

 1 /**
 2  * Note: The returned array must be malloced, assume caller calls free().
 3  */
 4 struct node {
 5         int num;
 6         int local;
 7 };
 8
 9 int cmp(const void * a,const void *b) {
10     struct node * aa = (struct node *)a;
11     struct node * bb = (struct node *)b;
12     if(aa->num == bb->num) {
13         return aa->local - bb->local;
14     }else{
15         return aa->num - bb->num;
16     }
17 }
18 int* twoSum(int* nums, int numsSize, int target) {
19
20     struct node* a = (struct node*)malloc(numsSize*(sizeof(struct node)));
21     int * vis = (int *)malloc(2*sizeof(int));
22     int beg = 0,end = numsSize-1,i;
23     for(i = 0; i < numsSize; i++) {
24         a[i].num = nums[i];
25         a[i].local = i+1;
26     }
27     qsort(a,numsSize,sizeof(a[0]),cmp);
28     for(; beg < end;){
29         int ans = target - a[beg].num;
30         while(1){
31             if(a[end].num == ans){
32                 if(a[beg].local < a[end].local){
33                     vis[0] = a[beg].local;
34                     vis[1] = a[end].local;
35                 }else {
36                     vis[0] = a[end].local;
37                     vis[1] = a[beg].local;
38                 }
39                 return vis;
40             }else if(a[end].num < ans){
41                 beg++;
42                 break;
43             }else {
44                 end--;
45             }
46         }
47     }
48     free(a);
49 }

(2)用c++提供的map模拟hash:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int,int>a;
 5         int i,len;
 6         len = nums.size();
 7         for(i = 0; i < len; i++) {
 8             int ans = target - nums[i];
 9             if(a.count(nums[i])){
10                 vector<int> res;
11                 int ans1,ans2;
12                 ans1 = i+1;
13                 ans2 = a[nums[i]];
14                 if(ans1 > ans2) {
15                     res.push_back(ans2);
16                     res.push_back(ans1);
17                     return res;
18                 }else {
19                     res.push_back(ans1);
20                     res.push_back(ans2);
21                     return res;
22                 }
23             }
24             a[ans] = i+1;
25         }
26     }
27 };
时间: 2024-11-06 11:57:44

一起刷LeetCode1-Two Sum的相关文章

leetcode第一刷_Minimum Path Sum

可以用递归简洁的写出,但是会超时. dp嘛.这个问题需要从后往前算,最右下角的小规模是已知的,边界也很明显,是最后一行和最后一列,行走方向的限制决定了这些位置的走法是唯一的,可以先算出来.然后不断的往前推算. 用distance[i][j]保存从当前位置走到最右下角所需的最短距离,状态转移方程是从distance[i+1][j]和distance[i][j+1]中选一个小的,然后再加上自身的. 代码很容易理解,这就是dp的魅力.空间上是可以优化的,因为当前状态只与后一行和后一列有关系. clas

leetcode-1 Two Sum 找到数组中两数字和为指定和

 问题描述:在一个数组(无序)中快速找出两个数字,使得两个数字之和等于一个给定的值.假设数组中肯定存在至少一组满足要求. <剑指Offer>P214(有序数组) <编程之美>P176 Que:Given an array of integers, find twonumbers such that they add up to a specific target number. The function twoSum should return indices ofthe tw

LeetCode1 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 t

leetcode1 Two Sum题解

题目大概意思就是,我给你传进来一个vector容器和一个target,vector相当于一个数组,现在问target是有数组种哪两个数组成的,返回两个下标,注意函数的返回类型也是vector类型的,所以一定要注意. 题目刚到手的时候,发现这个与各大OJ套路不太一样啊,也就是与ACM不太一样,我还傻傻的调整输出格式什么的,而且这个是完善一个类的成员函数,而不是提交一个可以运行的完整代码,觉得还是挺新奇的. 思路分析 最开始的时候,以为这个如果数据量不是很大的时候可以桶排序暴力破解啊,我见建立了一个

leetcode1 Two Sum的JavaScript解答总结

一.问题描述 翻译: 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字.你可以假设每一个输入只有一个结果.举例:输入:nums=[2, 7, 11, 15], target = 9输出:[0,1] 二.解答1.每出现一个值x,直接在数组中寻找是否有等于(target-x)的值 1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var twoSum = fu

简单算法汇总

一.全排列问题(Permutation) 问题描写叙述:即给定{1,2,3},返回123,132,213,231,312,321 <Permutation> 1)无顺序的全排列问题: 将序列P(n) = {1-.. n}的全排列问题看成P(n)={1,P(n-1)} + {2,P(n-1)}-..的问题.即确定第一个元素的值为1.然后和剩下n-1个元素的全排列结果组合到一起:然后再将1和剩下的每一个元素进行交换.然后和其剩下的n-1个元素排列结果进行组合.显然这是一个递归问题. // 递归实现

LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。

题目: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. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The so

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】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 true, as t

周刷题第一期总结(two sum and two numbers)

由于深深的知道自己是事件驱动型的人,一直想补强自己的薄弱环节算法,却完全不知道从哪里入手.所以只能采用最笨的办法,刷题.从刷题中遇到问题就解决问题,最后可能多多少少也能提高一下自己的渣算法吧. 暂时的目标是一周最少两道,可能会多做多想,工作再忙也会完成这个最低目标. Two sum: Given an array of integers, return indices of the two numbers such that they add up to a specific target. Y