leetcode 560. Subarray Sum Equals K & leetcode 1. Two Sum

本文介绍了解决LeetCode 560题(子数组和等于K)及LeetCode 1题(两数之和)的高效算法。通过使用哈希表来存储前缀和,可以将复杂度降低到O(n),从而快速找到符合条件的数组或元素对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 560. Subarray Sum Equals K

写在前面

本题不难,关键是要在题目刷了一些以后,能够在已有解法不满足条件的情况下快速跳出思维定势,回到问题本身。

题目描述

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

解题思路

一个很简单的想法就是暴力求解了,直接一个循环嵌套结束,但很明显这种解法不会满足面试要求。我们知道,题解的关键在于范围[i,j]的确定若 sum(i,j) = k ,则必有
sum(0,j)-sum(0,i) = k
因此,我们只需要记录每一次叠加求和后的值即可,这样得到的前置求和序列,若与k相减得到的数也存在于序列中,即说明上式成立,根据上述思路写出的代码如下:

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int,int> mMap;
        mMap[0] = 1;
        int sum = 0;
        int result = 0;
        for(auto&val:nums) {
            sum+=val;
            result += mMap[sum-k];
            mMap[sum]++;
        }
        return result;
    }
};

使用unordered_map(C++11)的目的在于对于无序存储的序列,hash方式的map速度更快。

leetcode 1. Two Sum

写在前面

本题与上一题基本是一样的,都是记录下preValue,然后用map的查找即可,因此代码也基本一致,这里把他们作为同一种类型的题目整理。这种解法的效率是O(n),只需要循环遍历一次数组。若本题改成排序后的数组,更快的解法是从数组两侧进行遍历求和。

题目描述

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].

解题思路

直接使用与560相同的解法。
代码如下:

class Solution {
public:

    vector<int> twoSum(vector<int>& nums, int target) {

        if(nums.empty()) return {};

        unordered_map<int,int> mHashMap;

        for(int i = 0;i<nums.size();++i) {
            auto val = target-nums[i];

            if(mHashMap.find(val)!=mHashMap.end()) {

                return {mHashMap[val],i};
            }
            mHashMap[nums[i]] = i;
        }

        return {};
        }
  };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值