【LeetCode016-017演算法/編程練習C++】3Sum Closest,九宮格IME//Sort函數

來源:互聯網
上載者:User

16. 3Sum Closest Total Accepted: 107572 Total Submissions: 352697 Difficulty: Medium Contributors: Admin

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

這道題要算出和target最接近的三個數之和

---------------------------自己寫的很愚笨的兩種方法,勉強通過測試------------------------------------------

//直接無腦迴圈通不過,加上一句==target就通過了……

class Solution {public:int threeSumClosest(vector<int>& nums, int target) {int result = nums[0] + nums[1] + nums[2];//    if(nums.size()<1000){for (int i = 0; i<nums.size() - 2; i++) {for (int ii = i + 1; ii<nums.size() - 1; ii++) {for (int iii = ii + 1; iii<nums.size(); iii++) {if (nums[i] + nums[ii] + nums[iii] == target)return target;if (abs(nums[i] + nums[ii] + nums[iii] - target)<abs(result - target))result = nums[i] + nums[ii] + nums[iii];}}}return result;}};

//自己寫的利用sort函數排序的第二種方法

sort排序之後就知道怎麼移動了,例如選定第一個,begin為第二個,end為最後一個,如果和大於target就把end往左移這樣,直到和和target一樣或者移動結束。

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {                int result=nums[0]+nums[1]+nums[2];        sort(nums.begin(),nums.end());//sort排序                for(int i=0;i<nums.size()-2;i++){            int begin=i+1;            int end=nums.size()-1;                    int sum=nums[i]+nums[begin]+nums[end];            if(sum==target)return target;                        while(sum!=target&&end-1>=begin){                 sum=nums[i]+nums[begin]+nums[end];                result= abs(sum-target)<abs(result-target)?sum:result;               if(sum>target){                end--;               }               if(sum==target)return target;                if(sum<target){                begin++;               }        }            }                return result;    }};
結果如圖:

 

17. Letter Combinations of a Phone Number Total Accepted: 119023 Total Submissions: 368508 Difficulty: Medium Contributors: Admin

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.

//天真的我以為*和#也要,浪費了不少時間

-------------------------------------我的解決方案,還做的挺久的其實---------------------------

class Solution {public:vector<string> letterCombinations(string digits) {vector<string>result;if (digits.size() == 0)return result;unordered_map<char, int>mapping;unordered_map<char, int>mapping2;for (int i = 0; i < 10; i++)mapping[i+'0'] = 3;for (int i = 0; i < 10; i++)mapping2[i + '0'] = i;mapping2['*'] = 10;mapping2['#'] = 11;mapping['0'] = 1;mapping['7'] = 4;mapping['9'] = 4;mapping['*'] = 1;mapping['#'] = 1;mapping['1'] = 1;char a[12][4] = { { ' ' },{},{ 'a','b','c' },{ 'a' + 3,'b' + 3,'c' + 3 },{ 'g','h','i' },{ 'j','k','l' },{ 'm','n','o' },{ 'p','q','r' ,'s' },{ 't','u','v' },{ 'w','x','y','z' },{ '+' },{} };//初始化int size = 1;for (int i = 0; i < digits.size(); i++) {size *= mapping[digits[i]];}string useless = "";for (int i = 0; i < size; i++)result.push_back(useless);int round ;round = size;for (int i = 0; i < digits.size(); i++) {for (int ii = 0; round!=0&&ii < size / round; ii++) {for (int j = 0; j < round; j++) {result[j + ii*round] += a[mapping2[digits[i]]][j*mapping[digits[i]] / round];}}round /= mapping[digits[i]];}return result;}};
運行結果:



Top Solution://好簡潔好簡潔,沒有真的去運行,看下思路以及表達吧,利用string來儲存真的漂亮了太多

vector<string> letterCombinations(string digits) {    vector<string> res;    string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};    res.push_back("");    for (int i = 0; i < digits.size(); i++)    {        vector<string> tempres;        string chars = charmap[digits[i] - '0'];        for (int c = 0; c < chars.size();c++)            for (int j = 0; j < res.size();j++)                tempres.push_back(res[j]+chars[c]);        res = tempres;    }    return res;}

還有一個:

vector<string> letterCombinations(string digits) {    vector<string> result;    if(digits.empty()) return vector<string>();    static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};    result.push_back("");   // add a seed for the initial case    for(int i = 0 ; i < digits.size(); ++i) {        int num = digits[i]-'0';        if(num < 0 || num > 9) break;        const string& candidate = v[num];        if(candidate.empty()) continue;        vector<string> tmp;        for(int j = 0 ; j < candidate.size() ; ++j) {            for(int k = 0 ; k < result.size() ; ++k) {                tmp.push_back(result[k] + candidate[j]);            }        }        result.swap(tmp);    }    return result;}

已經十二點了竟然,先去吃個飯,祝刷題愉快





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.