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:
自己练习代码如下:
其他人哈希表的方法, 目前还不是很了解哈希表的概念。
试着去做个笔记,哈希就是通过元素的一些性质或者属性,通过寻找哈希函数,将这个性质的关键值通过哈希函数映射到一个存储地址上,也就是获得该元素的哈希码,也即散列码。一般而言,哈希是一种将较长长度的信息进行压缩的一个过程。该题利用哈希表代码如下:
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 笔记27 Two Sum III - Data structure design
- Leetcode解题笔记 1.Two Sum [Easy]
- [leetcode笔记] Two-sum
- leetcode解题笔记:Two sum系列解题思路
- LeetCode刷题笔记(Two Sum)
- LeetCode 1 — Two Sum(C++ Java Python)
- 【LeetCode】Two Sum && 【九度】题目1352:和为S的两个数字
- LeetCode:Two Sum
- leetcode: Two Sum
- LeetCode 笔记系列一 Median of Two Sorted Arrays
- Leetcode_two-sum (c++ and python version)
- [Leetcode] Two Sum (Java)
- Two Sum-----LeetCode
- LeetCode(Two Sum)
- LeetCode之Two Sum
- Two Sum Leetcode 解法实现
- leetcode:Two Sum
- LeetCode题解:Two Sum
- leetcode Two Sum
- LeetCode Two Sum 两数之和