刷LeetCode(1)——两数相加
来源:互联网 发布:linux系统下删除用户 编辑:程序博客网 时间:2024/06/05 13:35
刷LeetCode(1)——两数相加
Code it now! https://leetcode.com/problems/two-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, 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].
题目比较简单,直接通过暴力方法来进行求解。
#include <vector>#include <iostream>#include <algorithm>using namespace std;class Solution {public: static vector<int> twoSum(vector<int>& nums, int target) { vector<int> v(2,0); const int len = nums.size(); for( int i=0;i<len;++i) { for( int j=i+1;j<len;++j) { if( nums[i] + nums[j] == target ) { v[0] = i; v[1] = j; return v; } } } return v; }};int main(){ vector<int> result; vector<int> vec(3,0); vec[0] = 3; vec[1] = 2; vec[2] = 4; result = Solution::twoSum(vec,6); for( vector<int>::iterator iter=result.begin(); iter != result.end(); ++iter) { cout << " " << (*iter); } cout << endl;}
大家如果有好的办法可以一起讨论讨论。
阅读全文
0 0
- 刷LeetCode(1)——两数相加
- 【LeetCode】- Two Sum(两数相加)
- LeetCode OJ 之 Add Two Numbers (”两数“相加)
- LeetCode 2. Add Two Numbers(两数相加)
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- 两数相加问题
- 算法:两数相加
- 两数相加
- 汇编两数相加
- [LeetCode]371.Sum of Two Integers两数相加
- Leetcode刷题记——67. Add Binary(二进制数相加)
- XMLHttpRequest 实现两数相加
- leetcode——Two Sum 两数之和(AC)
- leetcode 之 二进制数相加
- [LeetCode]2 两个数相加
- LeetCode 258 Add Digits(数字相加,数字根)
- 不用加减乘除完成两数相加
- 两数相加求进位次数
- centos7 下Nginx安装配置
- Android Studio 开发常遇到的SDK版本的问题
- [Err] 1044
- 1090. Highest Price in Supply Chain (25)
- android将一个long型转成时间字符串
- 刷LeetCode(1)——两数相加
- 取随机数的两种方法
- IntelliJ IDEA 实用快捷键
- Matlab plot函数
- python字典
- es 基本语法 使用 案例
- mysql schema设计方法
- A+B Format
- 资讯精选 | 各国加强网络安全法规建设和隐私保护