LeetCode Algorithm 0016 - 0020

LeetCode Algorithm 0016 - 0020



0016 - 3Sum Closest (Medium)

Problem Link: https://leetcode.com/problems/3sum-closest/description/

Description

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/3sum-closest/description/

namespace P16ThreeSumClosest
{
    class Solution
    {
        public:
        int threeSumClosest(vector<int>& nums, int target)
        {
            // 没有3个数
            if (nums.empty() || nums.size() < 3)
            {
                return -1;
            }

            // 排序
            sort(nums.begin(), nums.end());
        
            int result = nums[0] + nums[1] + nums[nums.size() - 1];

            for (size_t i = 0; i < nums.size() - 2; i++)
            {
                int leftIndex = i + 1;
                int rightIndex = nums.size() - 1;

                while (leftIndex < rightIndex)
                {
                    int sum = nums[i] + nums[leftIndex] + nums[rightIndex];
                    if (sum > target)
                    {
                        rightIndex--;
                    }
                    else
                    {
                        leftIndex++;
                    }

                    if (abs(sum - target) < abs(result - target))
                    {
                        result = sum;
                    }
                }
            }

            return result;
        }
    };
}


0017 - Letter Combinations of a Phone Number (Medium)

Problem Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Description

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

question 17

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

namespace P17LetterCombinationsOfAPhoneNumber
{
    class Solution
    {
        public:
        vector<string> letterCombinations(string digits)
        {
            if (digits.empty())
            {
                return vector<string>();
            }

            unordered_map<char, string> map;
            map['0'] = " ";
            map['1'] = "*";
            map['2'] = "abc";
            map['3'] = "def";
            map['4'] = "ghi";
            map['5'] = "jkl";
            map['6'] = "mno";
            map['7'] = "pqrs";
            map['8'] = "tuv";
            map['9'] = "wxyz";

            vector<string> result = NextLetters(map, digits, { "" });
            return result;
        }

        private:
        vector<string> NextLetters(unordered_map<char, string> map, string digits, vector<string> lastLetters)
        {
            if (digits.empty())
            {
                return lastLetters;
            }

            if (digits[0] < '0' || digits[0] > '9')
            {
                runtime_error e = runtime_error(
                    "ValueError: invalid literal for int() with base 10: " + digits[0]);
                throw e;
            }

            vector<string> letters = vector<string>();
            for (size_t i = 0; i < lastLetters.size(); i++)
            {
                for (size_t j = 0; j < map[digits[0]].size(); j++)
                {
                    string letter = lastLetters[i];
                    letter.push_back(map[digits[0]][j]);
                    letters.push_back(letter);
                }
            }

            return NextLetters(map, digits.substr(1), letters);
        }
    };
}


0018 - 4Sum (Medium)

Problem Link: https://leetcode.com/problems/4sum/description/

Description

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/4sum/description/

namespace P18FourSum
{
    class Solution
    {
        public:
        vector<vector<int>> fourSum(vector<int>& nums, int target)
        {
            if (nums.size() < 4)
            {
                return {};
            }

            // 排序
            sort(nums.begin(), nums.end());

            vector<vector<int>> results = {};
            FindSum(nums, 0, target, 4, {}, results);
            return results;
        }

        private:
        void FindSum(vector<int>& nums,
                     int startIndex, 
                     int target, 
                     int numCount, 
                     vector<int> result, 
                     vector<vector<int>>& results)
        {
            if (numCount < 2)
            {
                return;
            }

            int size = nums.size();
            if (numCount != 2)
            {
                for (int i = startIndex; i < size - numCount + 1; i++)
                {
                    if (target < nums[i] * numCount || target > nums[size - 1] * numCount)
                    {
                        break;
                    }

                    if (i == startIndex || (i > startIndex && nums[i - 1] != nums[i]))
                    {
                        vector<int> cur = vector<int>(result);
                        cur.push_back(nums[i]);
                        FindSum(nums, i + 1, target - nums[i], numCount - 1, cur, results);
                    }
                }
            }
            else
            {
                int leftIndex = startIndex, rightIndex = size - 1;
                while (leftIndex < rightIndex)
                {
                    if (nums[leftIndex] + nums[rightIndex] == target)
                    {
                        vector<int> cur = vector<int>(result);
                        cur.push_back(nums[leftIndex]);
                        cur.push_back(nums[rightIndex]);
                        results.push_back(cur);
                        leftIndex++;
                        rightIndex--;
                        while (leftIndex < rightIndex && nums[leftIndex] == nums[leftIndex - 1])
                        {
                            leftIndex++;
                        }
                        while (leftIndex < rightIndex && nums[rightIndex] == nums[rightIndex + 1])
                        {
                            rightIndex--;
                        }
                    }
                    else if (nums[leftIndex] + nums[rightIndex] < target)
                    {
                        leftIndex++;
                    }
                    else
                    {
                        rightIndex--;
                    }
                }
            }
        }
    };
}


0019 - Remove Nth Node From End of List (Medium)

Problem Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

Description

Given a linked list, remove the n -th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

namespace P19RemoveNthNodeFromEndOfList
{
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL)
        {
        }
    };

    class Solution
    {
        public:
        ListNode* removeNthFromEnd(ListNode* head, int n)
        {
            ListNode* start = new ListNode(0);
            start->next = head;

            ListNode* right = start;
            for (int i = 0; i < n; i++)
            {
                right = right->next;
            }

            ListNode* left = start;
            while (right->next != NULL)
            {
                left = left->next;
                right = right->next;
            }

            left->next = left->next->next;

            return start->next;
        }
    };
}


0020 - Valid Parentheses (Easy)

Problem Link: https://leetcode.com/problems/valid-parentheses/description/

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  • 1. Open brackets must be closed by the same type of brackets.
  • 2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/valid-parentheses/description/

namespace P20ValidParentheses
{
    class Solution
    {
        private:
        unordered_map<char, char> brackets = { {'(', ')'}, {'[', ']'}, {'{', '}'} };

        public:
        bool isValid(string s)
        {
            if (s.empty())
            {
                return true;
            }

            stack<char> chStack;
            for (size_t i = 0; i < s.size(); i++)
            {
                if (brackets.find(s[i]) != brackets.end())
                {
                    chStack.push(s[i]);
                    continue;
                }

                if (chStack.size() == 0)
                {
                    return false;
                }

                if (brackets[chStack.top()] == s[i])
                {
                    chStack.pop();
                }
                else
                {
                    return false;
                }
            }

            return chStack.size() == 0;
        }
    };
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值