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
- LeetCode个人笔记-Two Sum(1)
- LeetCode笔记1--Two Sum
- LeetCode 学习笔记:Question 1、Two Sum
- LeetCode学习笔记[1]:Two Sum
- LeetCode小白菜笔记[1]:Two Sum
- 个人记录-LeetCode 1.Two Sum
- LeetCode笔记:1. Two Sum
- LeetCode笔记:1. Two Sum
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- 动态规划 最长上升(下降)子序列 SDNUOJ 1040 导弹拦截和最少拦截系统
- Impala源码之订阅发布系统的实现
- linux_进程间通信
- Swift3.0基础知识脑图02
- hdu1003
- LeetCode个人笔记-Two Sum(1)
- 【数据结构】:排序--选择排序
- 重装ubuntu14.04
- java面向对象的继承以及方法重写和重载
- 解决ajax无法给外部变量赋值
- 在不开启事件循环的线程中使用QTimer
- STL
- Spring Security 4.x 启用CSRF防御后logout只能是POST请求
- swift3.0基础知识脑图03