leetcode day1
总共有三种法, 其实我尝试过用迭代! 但是并不成功, 我想用递归(recursive)的原因是递归的三个要素, 以及这道题
为什么我会想用递归应为在之前的学习中用迭代的要素有三个
1.所有都有差不多的解决思路
2.每次迭代会将数据变小
3.找到base case就是什么时候可以
经过这次练习, 迭代应该再加一条,每次return的值都必须要和上一个递归有联系或者可以传递到上一个影响最终结果!
为什么能直接想到用HashTable?
HashTable 定义:
哈希表(Hash Table,也叫散列表),是根据键(Key)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做哈希函数,存放记录的数组称做哈希表 (链接:https://leetcode-cn.com/tag/hash-table/ 来源:力扣(LeetCode))
如何创建一个哈希表?
首先我们知道map是一个抽象的类, 而hashmap是其中一个来实现这个
Map<Integer,Integer>
HashTable 常用method
get(int index) //return the value
public int[] twoSum(int[] nums, int target) {
//this is hashmap way
Map<Integer, Integer> map = new HashMap();
int[] result = new int[2];
for(int i =0; i<nums.length; i++){
int complement = target - nums[i];
//Why you shoud store the number as key, because you can use the key to find the value which is return the complement index.
if(map.containsValue(complement)){
result[0]= i;
result[1] = complement;
return result;
}
map.put(nums[i],i);
}
return result;
}
首先是最直接的办法,用loop, 两个loop。
public int[] twoSum(int[] nums, int target) {
//target is the sum
//direct way
int[] result = new int[2];
for(int i =0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(nums[i]+nums[j]==target){
result[0] = i;
result[1] = j;
}
}
}
return result;
}