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; 
        }
    };
    

      

  • 相关阅读:
    POJ 1321 棋盘问题
    算法导论 4.1 最大子数组问题
    矩阵快速幂
    固定定位
    HTML排版
    CSS笔记2
    HDU 1796 How many integers can you find(容斥原理)
    HDU 2147 kiki's game(博弈经典题)
    HDU 1846 Brave Game(巴什博弈超简单题)
    HDU 4704 Sum(隔板原理+组合数求和公式+费马小定理+快速幂)
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5175148.html
Copyright © 2011-2022 走看看