Leet Code OJ 1. Two Sum [Difficulty: Easy]
来源:互联网 发布:风机 scada 数据分析 编辑:程序博客网 时间:2024/05/16 03:07
Leet Code OJ 1. Two Sum [Difficulty: Easy]
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].
翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。
思路分析:
让所有元素两两想加,把满足条件的输出
MyCode
#include <stdio.h> #include <stdlib.h> #include <string> int main() { int nums[] = { 2, 7, 11, 15, 21 }; static int target = 9; int a = 0, b = 0; int num = sizeof(nums) / sizeof(nums[0]); for (int i = 0; i < num - 1; i++) { for (int j = i + 1; j < num ; j++) { int result = nums[i] + nums[j]; if (result == target) printf("%d + %d = %d \nThe results is [%d , %d]\n", nums[i], nums[j] , result , i , j); } } system("pause"); return 0; }
其实可以定义一个Vector用来存储符合条件的值,最后输出。
收集其他大神的解法如下,以供学习参考
C++ 解法1
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; vector<int> res; for (int i = 0; i < nums.size(); ++i) { m[nums[i]] = i; } for (int i = 0; i < nums.size(); ++i) { int t = target - nums[i]; if (m.count(t) && m[t] != i) { res.push_back(i); res.push_back(m[t]); break; } } return res; }};
C++ 解法2
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; for (int i = 0; i < nums.size(); ++i) { if (m.count(target - nums[i])) { return {i, m[target - nums[i]]}; } m[nums[i]] = i; } return {}; }};
1 0
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- hibernate 配置数据库方言
- 二叉树的所有路径
- C# Lambda表达式
- Linux配置启动项,自启动服务
- Android项目规范
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- 使用360镜像解决WordPress访问速度慢的问题
- TensorFlow学习笔记--1.0 版本的更改
- 李宏毅MLDS课程笔记9:Generative Adversarial Network(GAN)
- ubuntu16.04配置caffe(仅cpu)
- maven-war-plugin的乱码问题 (3 字节的 UTF-8 序列的字节 3 无效)报错
- 登陆界面
- 《APUE》读书笔记—第十二章线程控制
- git入门-----远程操作相关命令(remote 、push、fetch 、pull)