leetcode-two sum
来源:互联网 发布:黑客获取数据 编辑:程序博客网 时间:2024/06/05 15:54
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].
// two_sum.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <vector>//#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS 1//#include <hash_map>#include <unordered_map>#include <algorithm>using namespace std;/*****暴力搜索********/class Solution_1 {public:vector<int> twoSum(vector<int>& nums, int target) {vector<int>::iterator it = nums.begin();vector<int>::iterator its;vector<int> result;for (;it < nums.end();it++){for (its = it + 1;its < nums.end();its++){if (*its == target - *it){result.push_back(it - nums.begin());result.push_back(its- nums.begin());return result;}}}result.push_back(0);result.push_back(0);return result;}};/*******Two-pass Hash Table******/class Solution_2 {public:vector<int> twoSum(vector<int>& nums, int target) {vector<int>::iterator it = nums.begin();vector<int> result;unordered_map<int, int> hash;unordered_map<int, int>::iterator its=hash.begin();int comp;for (;it < nums.end();it++){hash[*it] =it - nums.begin(); //hash表赋值}for (it = nums.begin();it < nums.end();it++){comp = target - *it;its = hash.find(comp); //搜索的是hash[k,v]的kint k=it - nums.begin();if (its != hash.end() && its->second!=k ){result.push_back(it - nums.begin());result.push_back(its ->second);return result;}}result.push_back(0);result.push_back(0);return result;}};int main(){//cout << "HELLO WORLD"<<endl;Solution_2 s;int a[3] = {3,2,4};vector<int> nums;vector<int> result;for (int i=0;i < 3;i++){nums.push_back(a[i]); }//vector<int>::iterator it = nums.begin();//while (it<nums.end())//{//cout << *it << endl;//it++;//}result = s.twoSum(nums, 6);vector<int>::iterator its = result.begin();while (its<result.end()){cout << *its <<" ";its++;}system("pause"); return 0;}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- android 微信朋友圈相册封面裁剪的小秘密
- vue开发问题总结
- GC垃圾回收
- h3416最大流(未解决)
- web基础之Servlet执行过程
- leetcode-two sum
- 代理模式【介绍、静态代理、动态代理、入门、应用】
- 思科产品线
- codeforces #343d water tree(dfs+线段树)
- 精确小数点后两位
- 金融业对区块链必须有足够认识
- Yii 1.1使用函数updaAll方法
- 按照堆排序的方式原地进行升序排列
- jquery中的ajax方法详解