LeetCode | #1 Two Sum

来源:互联网 发布:java集合类型 编辑:程序博客网 时间:2024/03/29 00:06

终于开始在LeetCode上刷题了,第一弹:


微笑我是渣。


题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路:

  • 首先想到最暴力最简单的方法:双循环,两个两个地试。可以求解,但是超时,时间复杂度O(N^2)。
  • 然后想到把大于target的数去掉,少试一点,发现题目说的是整数,可以存在负数,此方法行不通。
  • 再然后想到排序:先快排,然后从头尾设两指针,相加大于target,尾指针-1,相加小于target,头指针+1。但是还要先排序,麻烦,时间复杂度其实就是排序的时间复杂度,因为头尾指针查找是线性的,O(N*logN)。
  • 最后找到别人的好方法:用HashMap,存数组的值和索引。遍历数组,以值为key,查map,没有就放进去,以target-key为目标value,查map,有就说明是这两个了。

import java.util.HashMap;public class TwoSum {/*//暴力求解,超时,O(N^2)public int[] twoSum(int[] numbers, int target) {int size = numbers.length;int[] rtn = new int[2];for(int i=0; i<size; i++){for(int j=i+1; j<size; j++){if(numbers[i]+numbers[j] == target){rtn[0] = i+1;rtn[1] = j+1;}}}return rtn;            }*///HashMap查找元素时间为常数,O(N)public int[] twoSum(int[] numbers, int target) {int size = numbers.length;int[] rtn = new int[2];HashMap<Integer, Integer> nums = new HashMap<>();for(int i=0; i<size; i++){int k = numbers[i];if(nums.get(k) == null){nums.put(k, i);}int d = target-k;if(nums.get(d) != null && nums.get(d) != i){rtn[0] = nums.get(d)+1;rtn[1] = i+1;break;}}return rtn;            }public static void main(String[] args) {TwoSum test = new TwoSum();int[] t = test.twoSum(new int[]{0,7,11,0}, 0);System.out.println(t[0]+","+t[1]);}}

Map学习:

        Map的基本思想是映射表(关联数组),维护的是键值对,用键查值。Map的实现有HashMap,TreeMap,LinkedHashMap,IdentityHashMap等,在效率、键值对保存方式、判定键等价的策略等方面不同。

  • HashMap用散列码(对象的hashCode())对键进行快速查询。散列码是“相对唯一”的,代表对象的int值,将对象的某些信息进行转码而生成,hashCode()是根类Object的方法,每个对象都有。插入和查询“键值对”的开销是固定的。
  • LinkedHashMap迭代遍历时,取出的“键值对”的顺序是其插入次序,因为它用链表维护内部次序。
  • TreeMap基于红黑树实现,查看“键”或“键值对”时,会被排序(由Comparable或Comparator决定)。
  • IdentityHashMap使用==代替equals()对“键”进行比较。


散列详解:

        存储一组元素最快的数据结构是数组,用它来表示键的信息(不是键本身)。因为数组不能调整容量,但Map中的保存数量是不确定的,所以数组不直接保存键本身,而是通过键对象产生一个数字作为数组下标,这个数字就是散列码。注意:不同对象的散列码可以相同,不同键可能查到数组的同一下标,所以数组也不直接保存值,而是保存值的list,对list中的值使用equals()方法进行线性查询。



        HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。


0 0
原创粉丝点击