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     }
  • 相关阅读:
    【Java】_2_Java程序入门第五课
    【算法和数据结构】_3_线性结构_栈
    Windows程序设计_17_鼠标_1
    网络基础知识1:集线器,网桥,交换机
    [hyddd安全性测试笔记2]浅淡静态代码分析工具
    [Ruby小记]初试~
    Arp攻击实战
    [hyddd安全性测试笔记1]URL Encode and URL Decode
    网络嗅探技术浅析
    Session小记
  • 原文地址:https://www.cnblogs.com/heruonan/p/8317096.html
Copyright © 2011-2022 走看看