zoukankan      html  css  js  c++  java
  • LeetCode1---两数之和

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;

    /**
    *功能描述 :两数之和
    * @author lkr
    * @date 2019/3/5
    */
    public class Solution1 {
    //暴力法
    public static int[] twoSum(int[] nums, int target) {
    int[] arr = new int[2];
    for(int i=0;i<nums.length;i++){
    for(int j=i+1;j<nums.length;j++){
    int sum = nums[i] + nums[j];
    if(target == sum){
    arr[0] = i;
    arr[1] = j;
    }
    }
    }
    return arr;
    }

    //一遍哈希表
    public static int [] oneHashtable(int[] nums,int target){
    Map<Integer,Integer> map = new HashMap();
    for (int i=0;i<nums.length;i++){
    int value = target - nums[i];
    if(map.containsKey(value)){
    /*int[] arr = {map.get(value),i};
    return arr;*/
    return new int[] {map.get(value),i};//为什么map.get(value)在前面?
    }
    map.put(nums[i],i);
    }
    throw new IllegalArgumentException("NO TWO SUM SOLUTION");
    }

    public static void main(String[] args){
    int [] nums = {2,7,11,15,9};
    int target = 20;
    //int [] arr = twoSum(nums,target);
    int [] arr = oneHashtable(nums,target);
    System.out.println(Arrays.toString(arr));
    }
    }
  • 相关阅读:
    Creative Cloud 无法连接问题
    HTTP_PROXY
    <video> controlsList
    Electron 问题
    含神经网络的离线AI翻译 APP

    (转载)移动Web开发技巧汇总
    2014年总结
    转载(web app变革之rem)
    火狐不支持backgroundPosition的js插件
  • 原文地址:https://www.cnblogs.com/turningli/p/10474374.html
Copyright © 2011-2022 走看看