力扣刷题笔记day02--两数之和,合并两个有序数组

1.两数之和

题目:

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

该题可用递归法设置两个for循环暴力求解,但该法时间复杂度较高。此处我们借助hashmap求解。先将数组中的元素从左到右依次放入hashmap,并比较与target的差,若这个差值正好与放入元素一致,则返回两元素的下标。

class solution{
    public int [] towsum(int [] nums, target){
        Map<integer,integer> storenum = new HashMap<>(nums.length,1);
        int [] result = new int [2];
        for(int i = 0; i < nums.length; i++){
            another = target - nums[i];
            anotherindex = storenum.get(another);
            if(null != another){
                result[0] = i;
                result[1] = anotherindex;

            }
            else{
                storenum.put(nums[i], i);
      
            }            
        }
        return result
    }
}

2.合并两个有序数组

题目:

给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。请你合并 nums2 到 nums1 中,使合并后的数组同样按非递减顺序 排列。

注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。

该题我们采用逐一比较的方式进行合并。将数组n1与n2的元素逐个比较,小的放入临时数组中,若某数组中的元素全部取完,则改为取另一数组中的元素。

 

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int k = m+n;
        int [] temp = new int [k];
        for(int index = 0, nums1index = 0, nums2index = 0; index < k; index++){
            if(nums1index >= m){
                temp[index] = nums2[nums2index++];
            }
            else if(nums2index >= n){
                temp[index] = nums1[nums1index++];
            }
            else if(nums1[nums1index] < nums2[nums2index]){
                temp[index] = nums1[nums1index++];
            }
            else{
                temp[index] = nums2[nums2index++];
            }
        }
        for(int i = 0; i<k; i++){
            nums1[i] = temp[i];
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

滴水穿石ing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值