zoukankan      html  css  js  c++  java
  • 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 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

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
    //   int a[] = {0,0};
    //     int len=numbers.length;
    //     int mid,left,right;
    //     for(int i=0;i<len;i++){
    //         for(int j=0;j<i;j++){
    //             if(numbers[i]+numbers[j]==target){
    //                 a[0]=j+1;
    //                 a[1]=i+1;
    //                 return a;
    //             }
    //         }
    //     }
    //         return null;
    
    //第一种暴力解法通过可能是因为case的问题 O(n^2)     第二个for循环换成for(int j=i+1;j<len;j++)就超时了
    //用HashMap的原因是containsKey查找效率高O(nlogn)
            int[] a = new int[2];
            HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
            for(int i=0;i<numbers.length;i++){
                if(map.containsKey(target-numbers[i])){
                    a[1]=i+1;
                    a[0]=map.get(target-numbers[i])+1;
                    return  a;
                }
                map.put(numbers[i], i);
            }
            return  null;
            
        }
    }
  • 相关阅读:
    网页加载进度条
    BFC
    Java — 基础语法
    Python — 多进程
    Python — 进程和线程
    Python — 面向对象进阶2
    Python — 面向对象编程基础
    Linnux 05
    Linnux 04
    Linnux 03
  • 原文地址:https://www.cnblogs.com/gaoxiangde/p/4210291.html
Copyright © 2011-2022 走看看