zoukankan      html  css  js  c++  java
  • [Locked] Two Sum

    Two Sum II - Input array is sorted

    Given an array of integers that is already sorted in ascending order, 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

    代码:

    vector<int> index(vector<int> numbers, int target) {
        vector<int> vi;
        int begin = 0, end = int(numbers.size() - 1), sum = numbers[begin] + numbers[end];
        while(sum != target) {
            sum > target ? end-- : begin++;
            sum = numbers[begin] + numbers[end];
        }
        vi.push_back(begin + 1);
        vi.push_back(end + 1);
        return vi;
    }

    Two Sum III - Data structure design

    Design and implement a TwoSum class. It should support the following operations: add and find.

    add - Add the number to an internal data structure.
    find - Find if there exists any pair of numbers which sum is equal to the value.

    For example,

    add(1); add(3); add(5);
    find(4) -> true
    find(7) -> false

    代码:

    class Solution {
    private:
        unordered_multiset<int> hash;
        
    public:
        void add(int num) {
            hash.insert(num);
            return;
        }
        bool find(int target) {
            for(int num : hash) {
                if(target - num == num && hash.count(num) >= 2)
                    return true;
                else if(hash.find(target - num) != hash.end())
                    return true;
            }
            return false;
        }
    };
  • 相关阅读:
    HDU 2013(递归)
    紫书搜索 习题7-6 UVA
    紫书搜索 习题7-4 UVA
    紫书搜索 习题7-3 UVA
    紫书搜索 习题7-2 UVA
    紫书搜索 习题7-1 UVA
    紫书搜索 例题7-10 UVA
    紫书搜索 例题7-13 UVA
    紫书搜索 例题7-12 UVA
    紫书搜索 例题7-9 UVA
  • 原文地址:https://www.cnblogs.com/littletail/p/5201230.html
Copyright © 2011-2022 走看看