Leetcode- 16-20题 题解

163Sum Closest

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

    For example, given array S = {-1 2 1 -4}, and target = 1.

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

题意:从一个给定的数组中选定3个数,使它们的和与target尽可能的接近,输出这个数
解析:和15题一样。
代码:

//和15一样的思路
class Solution {
public:
    int Two_sum(int l, int r, int target, vector<int> &nums, int i) {
        vector<int> s;
        int ans, f = 0;
        while(l < r)
        {
            if(nums[l] + nums[r] == target) return target + nums[i];
            else if(nums[l] + nums[r] < target)
            {
                if(!f || abs(target - nums[l] - nums[r]) < abs(target - ans)) f = 1, ans = nums[l] + nums[r];
                l++;
            }
            else
            {
                if(!f || abs(target - nums[l] - nums[r]) < abs(target - ans)) f = 1, ans = nums[l] + nums[r];
                r--;
            }
        }
        return ans + nums[i];
    }
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int ans, f = 0;
        for(int i = 0; i < nums.size()-2; i++)
        {
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int cur = Two_sum(i+1, nums.size()-1, target - nums[i], nums, i);
            if(!f || abs(target - cur) < abs(target - ans)) f = 1, ans = cur;
        }
        return ans;
    }
};
17 Letter Combinations of a Phone Number

Given a digit string, 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.

Input:Digit string "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.

题意:模拟老年机键盘
解析:模拟
代码:
//dfs
class Solution {
public:
    string s[11] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> ans;
    void dfs(string &p, int cur, int len, string &digits)
    {
        if(cur == len)
        {
            ans.push_back(p);
            return ;
        }
        int x = digits[cur] - '0';
        for(int i = 0; i < s[x].size(); i++)
        {
            p += s[x][i];
            dfs(p, cur+1, len, digits);
            p = p.substr(0, p.length()-1);
        }
    }
    vector<string> letterCombinations(string digits) {
        int len = digits.length();
        if(len == 0) return ans;
        string str = "";
        dfs(str, 0, len, digits);
        return ans;
    }
};
18 4Sum

Given an array S of n integers, are there elements abc, and d in S 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.

For example, given array S = [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]
]
题意:问是否有四个数的和为target,把所有情况存起来,去下重
解析:和15题一个思路哈~
代码:
//详见3Sum
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> cur;
    void two_sum(int l, int r, vector<int> &nums, int target, int i, int j)
    {
        while(l < r)
        {
            if(nums[i]+nums[j]+nums[l]+nums[r] == target)
            {
                cur.clear();
                cur.push_back(nums[i]); cur.push_back(nums[j]);
                cur.push_back(nums[l]); cur.push_back(nums[r]);
                ans.push_back(cur);
                while(l < r && nums[l+1] == nums[l]) l++;
                while(l < r && nums[r-1] == nums[r]) r--;
                l++;
                r--;
            }
            else if(nums[i]+nums[j]+nums[l]+nums[r] < target) l++;
            else r--;
        }
    }
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        for(int i = 0; i < nums.size(); i++)
        {
            if(i > 0 && nums[i] == nums[i-1]) continue;
            for(int j = i+1; j < nums.size(); j++)
            {
                if(j > i+1 && nums[j] == nums[j-1]) continue;
                two_sum(j+1, nums.size()-1, nums, target, i, j);
            }
        }
        return ans;
    }
};
19 Remove Nth Node From End of List

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

For 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.
Try to do this in one pass.

题意:给你一个链表,删除倒数第n个元素
解析:见代码处
代码:
//一个快指针,一个慢指针,让快的先跑n-1下,然后两个指针一起跑,快指针为最后一个时,慢指针就是要删除的元素哈,注意边界就可以AC了

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *low = head, *p = head, *fast = head;
        for(int i = 1; i < n; i++) fast = fast->next;
        while(fast->next)
        {
            fast = fast->next;
            p = low;
            low = low->next;
        }
        if(low == head)
        {
            head = head->next;
            free(p);
            return head;
        }
        if(n == 1)
        {
            p->next = NULL;
            free(fast);
            return head;
        }
        p->next = low->next;
        free(low);
        return head;
    }
};
20Valid Parentheses

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

题意:判断合法的括号
解析:用栈模拟下
代码:
//单纯比较下就OK了
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        int len = s.length();
        for(int i = 0; i < len; i++)
        {
            if(s[i] == '(' || s[i] == '[' || s[i] == '{') st.push(s[i]);
            else
            {
                if(st.empty()) return false;
                if(s[i] == ')' && st.top() == '(') st.pop();
                else if(s[i] == ']' && st.top() == '[') st.pop();
                else if(s[i] == '}' && st.top() == '{') st.pop();
                else return false;
            }
        }
        if(!st.empty()) return false;
        return true;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值