TwoSum

1.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].

思路: 1.暴力破解(肯定可以做一部分的题目,但是并不是全都可以,肯定会时间超出)

    2.问题集中于  相等的数字不能重复使用,两数相加要等于目标数字;

    采取存1找1的方式,由于最后是获取的位置信息,所以我们可以将数组中的数字的位置存储在一个数组中.

   使用 unordered_map   函数  就是hashmap    unordered_map标准库

c++代码
#include<iostream> #include<vector> #include<Windows.h> #include<unordered_map> using namespace std; class Solution { public: vector<int> nums = { 5,4,3,2,4,2 }; public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m;//相当于词典 第一个是key  第二个是元素 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]; //printf("%d\n", m.count(t)); if (m.count(t) && m[t] != i) {//m.count(t) 查找是否有这个数字 可以选择不使用 map函数 然后 重新自定义一个函数 判断是否存在需要查找的那个数字 res.push_back(i);//第一个数字的位置 res.push_back(m[t]);//第二个数字的位置 break; } } return res; } void printList(vector<int> nums) { for (int i = 0; i < nums.size(); i++) { printf("%d\t", nums[i]); } } }; int main(void) { Solution s; vector<int> resu(5); resu = s.twoSum(s.nums, 5); s.printList(resu); system("pause"); }

 java代码 实现和 c++相差不大  都是使用了 map

import java.util.HashMap;
import java.util.Map;

class Solution {
    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 class TwoSum {
    public static void main(String[] args){
        Solution s = new Solution();
        int[] nums = {5,4,3,2,1,2,4,5,6};
        int[] resu ;
        resu = s.twoSum(nums,8);
        for(int i=0;i<resu.length;i++){
            System.out.println(resu[i]);
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/hearecho/p/9249810.html
今日推荐