zoukankan      html  css  js  c++  java
  • leetcode twosum

    题目描述

    给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
    你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
    假设给出的数组中只存在唯一解
    例如:

    给出的数组为 {2, 7, 11, 15},目标值为9
    输出 ndex1=1, index2=2

     
    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

     
    可以用双循环查找,O(n2)
    也可以遍历一遍,并放入map中,。
    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            map<int,int> m;
            vector<int> res;
            for(int i=0;i<numbers.size();++i)
            {
                int j = target - numbers[i];
                if(m.find(j) == m.end())
                {
                    m[numbers[i]]=i;
                }
                else{
                    res={m[j]+1, i+1};
                    return res;
                }
            }
        }
    };
  • 相关阅读:
    线程的同步之Synchronized的使用
    线程的优先级
    线程的状态和常用操作
    Eclipse设置代码模板Code Template
    Eclipse设置每行代码的长度
    Eclipse设置控制台字体
    Gradle 安装(Windows)
    DSL与GPL
    Windows 新增 Sublime Text3 右键快捷方式
    mvn install 上传 jar 包到Maven仓库
  • 原文地址:https://www.cnblogs.com/zl1991/p/12716402.html
Copyright © 2011-2022 走看看