zoukankan      html  css  js  c++  java
  • 【LeetCode】1

    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

    Tags: Array Hash Table

    Solution 1: Time Limit Exceeded
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> ret;
            if(nums.empty())return ret;
            for(int i=0;i<nums.size();i++){
                int x=target-nums[i];
                for (int j=i+1;j<nums.size();j++){
                    if(nums[j]==x){
                        ret.push_back(i+1);
                        ret.push_back(j+1);
                        break;
                    }
                }
            }
            return ret;
        }

    Solution 2: map

        vector<int> twoSum(vector<int>& nums, int target){
            vector<int> ret;
            map<int, int> m;
            for(int i=0;i<nums.size();i++){
                if(!m.count(nums[i]))
                    m.insert(make_pair(nums[i], i));
                if(m.find(target-nums[i])!=m.end()){
                    if(i>m[target-nums[i]]){
                        ret.push_back(m[target-nums[i]]+1);
                        ret.push_back(i+1);
                        break;
                    }
                }
            }
            return ret;
        }
  • 相关阅读:
    基本sql查询语句练习
    SZU:J38 Number Base Conversion
    SZU:B54 Dual Palindromes
    SZU:A66 Plastic Digits
    HOJ:2031 进制转换
    SZU:G34 Love code
    SZU:A25 Favorite Number
    Vijos:P1001谁拿了最多奖学金
    SZU:A26 Anagram
    SZU:A12 Jumping up and down
  • 原文地址:https://www.cnblogs.com/irun/p/4795924.html
Copyright © 2011-2022 走看看