LeetCode个人笔记-Two Sum(1)

来源:互联网 发布:淘宝易行堂 编辑:程序博客网 时间:2024/04/27 14:01

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].

自己练习代码如下:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int len = nums.length;        int[] indices = new int[2];        for(int i = 0;i < len;i++)            for(int j = i + 1; j < len;j++)            {                if(nums[i]+nums[j] == target)                {                    indices[0]=i;                    indices[1]=j;                }            }        return indices;    }}

其他人哈希表的方法, 目前还不是很了解哈希表的概念。

试着去做个笔记,哈希就是通过元素的一些性质或者属性,通过寻找哈希函数,将这个性质的关键值通过哈希函数映射到一个存储地址上,也就是获得该元素的哈希码,也即散列码。一般而言,哈希是一种将较长长度的信息进行压缩的一个过程。该题利用哈希表代码如下:


package leetcode;import java.util.Arrays;import java.util.Hashtable;public class Leetcode {public static void main(String[] args){Leetcode leetcode = new Leetcode();int[] anums=new int[]{1,3,5,7};int target =8;leetcode.twoSum(anums,target);System.out.println(Arrays.toString(leetcode.twoSum(anums,target)));}public int[] twoSum(int[] nums,int target){int[] a = new int[2];Hashtable<Integer,Integer> numbers= new Hashtable<Integer,Integer>();    for(int i =0 ;i<nums.length;i++){    Integer n=numbers.get(nums[i]);    if(n==null)numbers.put(nums[i], i);    n=numbers.get(target-nums[i]);    if(n!=null && n<i)    {    a[0]=n+1;    a[1]=i+1;    return a;    }    }    return a;}}



0 0
原创粉丝点击