LeetCode: 给定数组找目标和的下标索引数组(1,167,560,653)

---恢复内容开始---

1   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].
//函数参数 为目标数组的应用,和目标和,返回索引数组
vector<int> twoSum(vector<int> &numbers, int target)
{
    //数组元素是键,值是对应的指标
    unordered_map<int, int> hash;
    vector<int> result;
    for (int i = 0; i < numbers.size(); i++) {
        //看目标数减去numbers[i] 余数是多少
        int numberToFind = target - numbers[i];
        //看有没有这个余数的键值
        if (hash.find(numberToFind) != hash.end()) {
            //如果有 返回索引数组
            result.push_back(hash[numberToFind]);
            result.push_back(i);            
            return result;
        }
        //不然,更新hasn数组
        hash[numbers[i]] = i;
    }
    return result;
}

167  Given an array of integers that is already sorted in ascending order, 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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
//也可以使用以上的方法
vector<int> twoSum(vector<int>& numbers, int target) { int l = 0; int r = numbers.size() -1; while(l < r){ if(numbers[l] + numbers[r] == target){ //注意这个初始化方式 vector<int> res{l+1,r+1}; return res; } else if(numbers[l] + numbers[r] > target){ r--; } else{ l++; } } }
 

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

// hashmap + preSum
/*
    1. Hashmap<sum[0,i - 1], frequency>
    2. sum[i, j] = sum[0, j] - sum[0, i - 1]    --> sum[0, i - 1] = sum[0, j] - sum[i, j]
        k           sum      hashmap-key     -->  hashmap-key  =  sum - k
    3. now, we have k and sum.  
        As long as we can find a sum[0, i - 1], we then get a valid subsequence
        which is as long as we have the hashmap-key,  we then get a valid subsequence
    4. Why don't map.put(sum[0, i - 1], 1) every time ?
        if all numbers are positive, this is fine
        if there exists negative number, there could be preSum frequency > 1
*/    

/*
    for i, cum is the sum of nums[0] + nums[1] + ... + nums[i]. Assuming there is an item called 
    nums[j] in nums[0] + nums[1] + ... nums[j] + ... + nums[i], if nums[0] + nums[1] + ... + nums[j]
    equals to cum - k, then, the sum of subarray nums[j + 1] + nums[j + 2] + ... + nums[i] equals
    to cum - (cum - k) = k, it is one of the subarray which we are looking for. rec[cum - k] is
    the number of the subarray which begins at index 0 with sum cum - k.
*/
class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int cum=0;        // cumulated sum
        map<int,int> rec; // prefix sum recorder
        int cnt = 0;      // number of found subarray
        rec[0]++;         // to take into account those subarrays that begin with index 0
        for(int i=0;i<nums.size();i++){
            cum += nums[i];
            //sum[i, j] = sum[0, j] - sum[0, i - 1]
            //由于现在的结果是cum  为了凑出k我们还需要 cum - k 的个数
            cnt += rec[cum-k];
            rec[cum]++;
        }
        return cnt;
    }
};

653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST(二叉搜索树) such that their sum is equal to the given target.

Example 1:
Input:
                5
               / \
              3 6
              / \ \
             2 4 7

       Target = 9

     Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7

Target = 28

Output: False

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> set;
        return dfs(root, set, k);
    }
    
    bool dfs(TreeNode* root, unordered_set<int>& set, int k){
        if(root == NULL)return false;
        if(set.count(k - root->val))return true;
        set.insert(root->val);
        return dfs(root->left, set, k) || dfs(root->right, set, k);
    }
};

更多解法参考:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106059/JavaC++-Three-simple-methods-choose-one-you-like

猜你喜欢

转载自www.cnblogs.com/liwei3013/p/9761745.html