LeetCode习题笔记——Two Sum

Two Sum是LeetCode中最简单的例题之一,我们今天就从这个系列的题目开始练手,练习coding的算法以及算法的解析。

我们先从第一个题目开始看起:

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>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
            for (int j = i + 1; j < nums.size(); j++) {
                if (nums[i] + nums[j] == target) 
                    return {i, j};
            }
        }
    }

这个算法的时间复杂度为
O(n^2)
O(n2)

而当我们了解了更多有关数据结构的东西之后,仔细思考,利用哈希表的特性,我们可以将代码中的循环减少至一个,在循环中去遍历表中是否有符合条件的数即可,下面给出

利用哈希表的代码:

vector<int> twoSum(vector<int> &numbers, int target)
{
    
	unordered_map<int, int> hash;
	vector<int> result;
	for (int i = 0; i < numbers.size(); i++) {
		int numberToFind = target - numbers[i];

            //if numberToFind is found in map, return them
		if (hash.find(numberToFind) != hash.end()) {
                    //+1 because indices are NOT zero based
			result.push_back(hash[numberToFind] + 1);
			result.push_back(i + 1);			
			return result;
		}

            //number was not found. Put it in the map.
		hash[numbers[i]] = i;
	}
	return result;
}
时间复杂度为   O(n)O(n)

这个题目是比较典型的利用哈希表的特性从而减少算法复杂度的例题,难度不大,非常适合了解和巩固有关哈希表的概念和应用。


下面是Two Sum系列的最后一题(第二题和第一题大同小异,甚至更加简单):

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
这个题目是有关二叉排序树的,问题的核心是一样的。而二叉排序树(BST)是一颗已经排序好的树,它的中序遍历一定是递增的,即左子节点 < 根结点 < 右子节点。利用这个特性,可以将树先转化为一个排序的数列(链表),之后的操作便很简单了,下面给出利用二叉排序树特性的算法代码:

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> nums;
        inorder(root, nums);
        return findTargetInSortedArray(nums, k);
    }

private:
    void inorder(TreeNode* node, vector<int>& nums) {
        if (!node) return;
        inorder(node->left, nums);
        nums.push_back(node->val);
        inorder(node->right, nums);
    }

    bool findTargetInSortedArray(vector<int> a, int target) {
        for (int i = 0, j = a.size() - 1; i < j;) {
            int sum = a[i] + a[j];
            if (sum == target) {
                return true;
            }
            else if (sum < target) {
                i++;
            }
            else {
                j--;
            }
        }

        return false;
    }
};
利用二叉排序树的性质,放入数列中已经是排序好的,之后便是从两头遍历,如果和大于目标值,则让头部和尾部-1相加,反之同理。


以上就是Two Sum系列的习题分析和算法代码,这次我们复习了哈希表和BST的相关知识,而他们也是数据结构的重点知识,需要更加多的练习和实际操作,才能对这些数据结构和算法有更深的理解。


 







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值