LeetCodeOJ——1.Tow Sum
来源:互联网 发布:淘宝客pid 编辑:程序博客网 时间:2024/04/30 14:41
Tow Sum
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 solution.
*Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].*
解决思路:两个循环,遍历。
代码:
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ve; for(int i=0;i<nums.size()-1;i++){ for(int j=i+1;j<nums.size();j++){ if(nums[i]+nums[j]==target){ ve.push_back(i); ve.push_back(j); } } } return ve; }};
后记:这是我最开始想到的方法,并且也AC了。然而时间复杂度为O(n2)。后来看到了别人的方法,利用map(以空间换时间),将时间复杂度降至O(n)。
代码如下:
两遍遍历:
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution");}
一遍遍历:
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution");}
0 0
- LeetCodeOJ——1.Tow Sum
- leetcode 1. Tow Sum
- javascript —— tow
- 经典算法面试题系列(一)——tow sum
- LeetCode: Tow Sum (JavaScript)
- LeetCode : Tow Sum [java]
- leetcode-001 tow sum
- [leetcode]Tow Sum(java)
- 1 Tow Sum
- [LeetCode]--Tow Sum
- 【面试准备】letcode-Tow Sum
- leetcode 001 Tow Sum(java)
- LeetCode 1---Tow Sum
- 【LeetCodeOJ】Path Sum
- LeetCodeOJ Two Sum (python)
- LeetcodeOJ Two Sum
- LeetCodeOJ:1Two Sum
- LeetCodeOJ 3sum
- Java第三章习题3-7(1到n的阶乘和<=9999)
- Linux常用命令
- Cocos2D -- 添加点击侦听listener(基本格式、判断点击区域、拖拽跟随移动)
- List、Set和Map
- 页面静态化
- LeetCodeOJ——1.Tow Sum
- iOS使用setting bundle
- pure render中《Immutable 详解及 React 中实践》一文读后感
- Dalvik虚拟机和Java虚拟机的区别
- 关于C#连接oracle数据报System.Data.OracleClient 需要 Oracle 客户端软件 version 8.1.7 或更高版本
- AJAX应用
- 变态跳台阶
- 关于Android UI布局标签收藏
- 返回当前时间戳