leetcode刷题(java)——day01

博客围绕LeetCode两数之和问题展开,给出题目描述,即从整数数组中找出两数和为特定目标值的索引,且每个输入只有一个解、不能用同一元素两次。还介绍用Java 8解题,同时讲解了哈希的概念、散列函数、散列表,指出其相比数组和链表可减少寻值时间。

Two Sum

Question

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

use java8 to solution

import java.util.Hashtable;

/*
 * @lc app=leetcode id=1 lang=java
 *
 * [1] Two Sum
 */
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Hashtable<Integer,Integer> hashtable  =new Hashtable<Integer,Integer>();
        int i = 0;
        while ((i< nums.length)&& (hashtable.get(nums[i]) == null)){
            hashtable.put(target - nums[i], i);
            i++;
        }
        if(i<nums.length){
            return new int[]{hashtable.get(nums[i]),i};
        }
        return null;
    }
}

Next up is an understanding of Hash.

Hash :散列,通过关于键值(key)的函数,将数据映射到内存存储中一个位置来访问。这个过程叫做Hash,这个映射函数称做散列函数,存放记录的数组称做散列表(Hash Table),又叫哈希表

hash相对于数组和链表最大的好处就是,先对数据进行分类,再进行查找,减少了遍历的过程,从而大大减少了寻值的时间。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值