zoukankan      html  css  js  c++  java
  • #1 Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    解法1:暴力寻找,可以通过(网上说不可以,不知道为什么我的就可以)

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            //给定一个数组,求两个和等于目标值的下标,下标从1开始
            int sum = 0;
            vector<int> index;
            int length = nums.size();
            for(int i = 0; i < length; i++) {
                for(int j = length - 1; j > i; j--) {
                    sum = nums[i] + nums[j];
                    if(sum == target) {
                        index.insert(index.begin(), j + 1);
                        index.insert(index.begin(), i + 1);
                      break;  
                    }
                    else continue;
                }
            }
            return index;
              
        }
    };
    

    解法2:哈希表

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            //给定一个数组,求两个和等于目标值的下标,下标从1开始
            map<int, int> hash;
            vector<int> out(2);
            //赋值存入哈希表,建立映射关系,位置和键值对应 
            for(int i = 0; i < nums.size(); i++) {
                hash[nums[i]] = i;
            }
            for(int i = 0; i < nums.size(); i++) {
                //找到目标值的位置,且不等于本身的位置
                if(hash.find(target - nums[i]) != hash.end() && hash[target - nums[i]] != i) {
                out[0] = i + 1;
                out[1] = hash[target - nums[i]] + 1;
                break;    
                }
            }
            return out; 
        }
    };
    

      

  • 相关阅读:
    002-Linux下防火墙相关命令操作
    001-网卡配置
    vs2012中自带IIS如何让其他电脑访问
    001-Mono for android在vs2012中发布设置
    小知识:utf-8和utf8mb4字符集
    Maven 模块化开发
    JUnit 单元测试
    解决8080端口占用问题
    (三)Tomcat服务器 -------JavaWeb的学习之路
    (一)走进JavaWeb的世界 -------JavaWeb的学习之路
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5175148.html
Copyright © 2011-2022 走看看