您的位置:首页 > 其它

LeetCode个人笔记-Two Sum(1)

2017-03-01 22:45 246 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 哈希 TwoSum