• 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;
            
        }
    }
  • 相关阅读:
    删除链表的倒数第N个节点(java实现)
    Java多线程之volatile关键字《一》
    Utils
    分布式和集群
    java RMIC
    Log4j输出终端(Appender)详解
    使用存储过程并返回值与及返回值的获得方法
    groupBy
    group by java实现
    本机Font字体
  • 原文地址:https://www.cnblogs.com/gaoxiangde/p/4210291.html
Copyright © 2020-2023  润新知