leetcode001
来源:互联网 发布:大嘴视频软件 编辑:程序博客网 时间:2024/06/06 03:19
两和
问题描述
原文
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
翻译
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。
例:
给定nums = [2,7,11,15],target = 9,因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9,返回[ 0,1 ]。
- 法一
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>result; for (int i=0; i<nums.size(); i++) { for (int j=i+1; j<nums.size(); j++) { if (nums[i]+nums[j] == target) { result.push_back(i); result.push_back(j); break; } } } return result; }};
- 法二
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> mapping; vector<int> result; for (int i = 0; i < nums.size(); i++) { mapping[nums[i]] = i; } for (int i = 0; i < nums.size(); i++) { int searched = target - nums[i]; if ( mapping.at(searched) != i) { result.push_back(i); result.push_back(mapping[searched]); break; } } return result; }};
总结
法一的解决方法思路很简单直白,直接按照排列组合的方式去组合每一种可能,知道找到nums[i]+nums[j] = target。算法复杂度为n^2。
法二相对法一进行了一点改进,使用map容器先存好nums的键值对,直接只用一层循环遍历,target-nums[i] = search;然后直接在存好的mapping里面寻找。算法复杂度为2n
阅读全文
0 0
- LeetCode001
- leetcode001
- LeetCode001题解
- leetcode001 TwoSum
- leetcode001:3sum solution
- leetcode001:Two Sum
- leetcode001 Two Sum
- Two Sum - leetcode001
- Leetcode001-Two Sun
- leetcode001——Two Sum
- Leetcode001:twoSum的Java解法
- leetcode001-2Sum,3Sum
- Leetcode001--两数之和为指定数
- 【LeetCode001算法/编程练习C++】--twoSum //从816ms到16ms的优化过程
- Intent的初体验
- pkg-config 用法简介
- Caffe——python接口学习:生成deploy文件
- 解决UC浏览器、微信浏览器使用display:flex;的兼容性问题
- 数值数据编码
- leetcode001
- 二分查找之美:二分查找及其变体的正确性以及构造方式
- 【MyBatis】MyBatis Generator插件自动生成文件,generatorConfig.xml配置详解
- 今天聊聊闲话,付出还是有回报的,我帮过的朋友8台电脑帮我齐挖Zcash(ZEC)
- SpringBoot、JPA及MVC的学习
- Andrew Ng机器学习课程之学习笔记---牛顿方法
- Redis监控
- 博客已迁移
- 获取Android版本号