Two Sum leetcode第一题

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

  • 最开始使用两个for循环暴力之,但是提示超时,代码如下:
public class Solution {
    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for(int i = 0 ;i < nums.length; i++){
            for(int j = i+1 ;j < nums.length ;j++){
                if(nums[i]<nums[j] && nums[i]+nums[j] == target){
                    result[0] = i+1;
                    result[1] = j+1;
                    return result;
                }
            }
        }
        return result;
    }

    public static void main(String[] args){
        int[] nums = {2, 7, 11, 15,1,8};
        int target = 9;
        int[] result = new int[2];
        result =  twoSum(nums,target);

        System.out.println("index1="+result[0]+"  index2="+result[1]);
    }
}
  • 然后百度了下,看到有用map集合的,思考了下,代码如下:
import java.util.Hashtable;
public class Solution {
    public static int[] twoSum(int[] numbers, int target) {
       Hashtable<Integer,Integer> ht = new Hashtable<Integer,Integer>();
        int[] result = {0,0};
        for(int i = 0; i < numbers.length; i++){
            ht.put(numbers[i], i);
        }
        for(int i = 0; i < numbers.length; i++){
            int gap = target - numbers[i];
            if(ht.get(gap)!=null && ht.get(gap)>i){
                result[0] = i + 1;
                result[1] = ht.get(gap) + 1;
                return result;
            }
        }
        return result;
    }

    public static void main(String[] args){
        int[] nums = {2, 7, 11, 15,1,8};
        int target = 9;
        int[] result = new int[2];
        result =  twoSum(nums,target);

        System.out.println("index1="+result[0]+"  index2="+result[1]);
    }
}
  • HaspTable
    1、数组按顺序存储元素,通过元素的下标可非常方便地获得该元素。但反过来则比较困难,通常需要顺序查找。一般认为从元素查找元素所对应的存储位置最快方式是采用哈希表。
    2、哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
    public synchronized Object get(Object key)
    根据给定关键字key获取相对应的对象。
    public synchronized boolean containsKey(Object key)
    判断哈希表中是否包含关键字key。
    public synchronized boolean contains(Object value)
    判断value是否是哈希表中的一个元素。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值