zoukankan      html  css  js  c++  java
  • leetcode 刷题 数组类 Two Sum

    ---恢复内容开始---

    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  inclices 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 must assume that each input would have exactly one solution.

    Input :number ={2,7,11,15},target =9;

    Output :index1=1,index2=2

    给定一个整数数组,找到两个数字,这样它们就可以加到一个特定的目标数。
    函数二和应该返回两个数字的inclices,它们加起来到目标,在哪里。
    index1必须小于index2。请注意您返回的答案(包括index1和index2)
    不是从零开始的。
    您必须假定每个输入都只有一个解决方案。
    输入:数量= { 2、7、11、15 },目标= 9;
    输出:index1 = 1,index2 = 2

    ---恢复内容结束---

     1 public int[] twoSum(int[] nums, int target) {
     2         if (nums == null || nums.length <= 1) {
     3             return new int[2];
     4         }
     5         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
     6         // key = target - nums[i], just one solution
     7         for (int i = 0; i < nums.length; i++) {
     8             map.put(target - nums[i], i);
     9         }
    10         for (int i = 0; i < nums.length; i++) {
    11             Integer v = map.get(nums[i]);
    12             // can't use itself
    13             if (v != null && v != i) {
    14                 return new int[] { i + 1, v + 1 };
    15             }
    16         }
    17         return null;
    18     }
  • 相关阅读:
    迭代和列表生成式
    python递归函数
    python函数
    变量
    python第八课后整理
    python第八课
    python第七课
    python第六课
    python第五课
    微信端/企业微信端H5页面调试方法
  • 原文地址:https://www.cnblogs.com/heruonan/p/8317096.html
Copyright © 2011-2022 走看看