zoukankan      html  css  js  c++  java
  • 【leetcode】Two Sum (easy)

    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

    跟以前做过的都差不多,就是要定位下标。AC代码O(nlogn)

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> copyNumbers = numbers;
            vector<int> AddNum;
            vector<int> Result;
            sort(copyNumbers.begin(), copyNumbers.end()); //升序排序
            //确定两个加数
            for(int i = 0, j = copyNumbers.size() - 1; i < j; )
            {
                if(copyNumbers[i] + copyNumbers[j] == target)
                {
                    AddNum.push_back(copyNumbers[i]);
                    AddNum.push_back(copyNumbers[j]);
                    break;
                }
                else if(copyNumbers[i] + copyNumbers[j] < target)
                {
                    i++;
                }
                else
                {
                    j--;
                }
            }
            //定位两个加数
            for(int i = 0; i < numbers.size(); i++)
            {
                if(numbers[i] == AddNum[0] || numbers[i] == AddNum[1])
                {
                    Result.push_back(i + 1);
                }
            }
    
            return Result;
        }
    };
    
    int main()
    {
        Solution sol;
        vector<int> vec;
        vec.push_back(0);
        vec.push_back(4);
        vec.push_back(3);
        vec.push_back(0);
    
        vector<int> ans = sol.twoSum(vec, 0);
    
        return 0;
    }

    看答案,发现有O(n)的解法。用hash表,从头到尾判断 target-当前值 在vector中是否存在O(1),因为用了hash.

    O(n) runtime, O(n) space – Hash table:

    We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

    public int[] twoSum(int[] numbers, int target) 
    {   Map
    <Integer, Integer> map = new HashMap<>();   for (int i = 0; i < numbers.length; i++) {     int x = numbers[i];     if (map.containsKey(target - x)) {       return new int[] { map.get(target - x) + 1, i + 1 };     }     map.put(x, i);   }   throw new IllegalArgumentException("No two sum solution"); }
  • 相关阅读:
    XV6文件系统
    XV6锁
    PC硬件以及引导加载器
    XV6第一个进程
    XV6操作系统接口
    XV6环境搭建及注意事项
    XV6文件系统
    XV6上下文切换
    少走弯路的十条忠告
    LIBCMTD.lib与libcpmtd冲突的解决方法。
  • 原文地址:https://www.cnblogs.com/dplearning/p/4110024.html
Copyright © 2011-2022 走看看