设为首页 加入收藏

TOP

leetcode---------------Two Sum
2015-07-20 17:24:48 来源: 作者: 【 】 浏览:3
Tags: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

题目意思是:给定一个数组,给一个数target,在数组找到两个数的和为target,找出这个两个数的位置,其下标索引从1开始算起。

思路:

方法一:暴利求,两个for循环遍历,找到退出,复杂度O(n2)

方法二::hash 用一个哈希表,存储每个数对应的下标,复杂度 O(n).

方法二解答:

?

class Solution 
{
public:
	vector
  
    twoSum(vector
   
     &numbers, int target) { unordered_map
    
      mapping; vector
     
       result; for (int i = 0; i < numbers.size(); ++i) { mapping[numbers[i]] = i; } for (int i = 0; i < numbers.size(); ++i) { const int tmp = target - numbers[i]; if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i) { result.push_back(i+1); result.push_back(mapping[tmp] + 1); break; } } return result; } };
     
    
   
  
在线推送结果为:

?


Question:
Similar to Question [1. Two Sum], except that the input array is already sorted in
ascending order.

问题:假如数组是有序的话我们就可以同时从头尾开始向中遍历。

?

class Solution
{
public:
	vector
  
    twoSum(vector
   
     &numbers, int target) { vector
    
      result; int i = 0; int j = numbers.size() - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum < target) ++i; else if (sum>target) --j; else { result.push_back(i + 1); result.push_back(j + 1); break; } } return result; } };
    
   
  


?

?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇codeforces--Spreadsheets(模拟) 下一篇输入两个正整数,求其最大公约数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C 内存管理 | 菜鸟教 (2025-12-26 20:20:37)
·如何在 C 语言函数中 (2025-12-26 20:20:34)
·国际音标 [ç] (2025-12-26 20:20:31)
·微服务 Spring Boot (2025-12-26 18:20:10)
·如何调整 Redis 内存 (2025-12-26 18:20:07)