算法学习Day1-递归

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值