leetcode个人刷题笔记(持续更新)

版权声明:转载请声明出处,谢谢~ https://blog.csdn.net/what951006/article/details/78006162

1. Two Sum

原题地址
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]

解:

/*这题基本上没有什么难度,两个for一套解决问题*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> vec_result;

        for(int i=0;i<nums.size();++i)
        {
            for(int j=i+1;j<nums.size();++j)
            {
                if(nums[i]+nums[j] == target)
                {
                    vec_result.push_back(i);
                    vec_result.push_back(j);
                }
            }
        }
        return vec_result;
    }
};

2. Add Two Numbers

原题地址
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解:

//其实我在练习递归。解释我放在代码中
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
bool g_bCarry=false;
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int nValue1=0,nValue2=0;
        if(g_bCarry && !l1&&!l2)//进位并且到达末端
        {
            ListNode* pNode=new ListNode(1);
            g_bCarry=false;
            return pNode;
        }
        if(!l1 && !l2)
        {
            g_bCarry=false;
            return NULL;
        }
        if(l1)
            nValue1=l1->val;
        if(l2)
            nValue2=l2->val;
        if(g_bCarry)
            nValue1+=1;      
        if(nValue1+nValue2 >= 10)
            g_bCarry=true;
        else
            g_bCarry=false;

        ListNode* pNode=new ListNode((nValue1+nValue2)%10);
        ListNode* pNext=NULL;
        if(l1 && l2)
            pNext= addTwoNumbers(l1->next,l2->next);
        else if(!l1 && l2)
            pNext= addTwoNumbers(NULL,l2->next);
        else if(l1 && !l2)
            pNext= addTwoNumbers(l1->next,NULL);
        else
            pNext= addTwoNumbers(NULL,NULL);
        pNode->next=pNext;
        return pNode;
    }
};

3. Longest Substring Without Repeating Characters

原题地址
Given a string, find the length of the longest substring without repeating characters.
Examples:

Given “abcabbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. >Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

解:

这个题我竟然没有理解到意思!

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:

nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

解:

//stl就是好,好的不得了,直接把nums2的添加到num1去,然后再使用sort来排序,再在num1找出来就好了!
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        double result;
        for_each(nums2.begin(),nums2.end(),[&](int value){
            nums1.push_back(value);
        });
        sort(nums1.begin(),nums1.end(),greater<int>());
        if(nums1.size()%2==0)
        {

                return ((double)nums1[nums1.size()/2-1]+nums1[nums1.size()/2])/2;
        }
        else
        {
                return nums1[nums1.size()/2];
        }
    }
};

5. Longest Palindromic Substring

原题链接
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: “babad”
Output: “bab”

Note: “aba” is also a valid answer.

Example:

Input: “cbbd”
Output: “bb”

解:

/*遍历字符串,s[index - 1] == s[index + 1]用于判断这种情况 aabaa,
s[index-1] == s[index]用于判断 acbbca即重复的bb开始。
*/
class Solution {
public:
    string longestPalindrome(string s)
    {
        string strResult;
        string strTemp,strTemp2;
        bool bMatchFinished = false;
        if (s.length() <= 2) return s;
        for (int index = 1; index<s.length(); ++index)
        {
            if (s[index - 1] == s[index + 1])
            {
                strTemp = "";
                bMatchFinished=false;
                for (int nPos = 0; nPos < index; ++nPos)
                {
                    bMatchFinished = true;
                    if (s[index  -1- nPos] != s[index +1 + nPos]) break;
                    else strTemp += s[index -1- nPos];
                }
                if (bMatchFinished)
                {
                    strTemp2 = strTemp;
                    reverse(strTemp2.begin(), strTemp2.end());
                    strTemp2 += s[index];
                    strTemp.insert(0,strTemp2);
                }
                if (strTemp.length() > strResult.length())
                    strResult = strTemp;
            }
            if (s[index-1] == s[index])
            {
                strTemp = "";
                bMatchFinished=false;
                for (int nPos = 0; nPos<index; ++nPos)
                {
                    bMatchFinished = true;
                    if (s[index-1 - nPos] != s[index + nPos]) break;
                    else strTemp += s[index + nPos];
                }
                if (bMatchFinished)
                {
                    strTemp2= strTemp;
                    reverse(strTemp2.begin(), strTemp2.end());
                    strTemp.insert(0,strTemp2);
                }
                if (strTemp.length() > strResult.length())
                    strResult = strTemp;
            }
        }
        if (strResult.empty())
        {
            strResult= s[0];
            return strResult;
        }
        return strResult;
    }
};

6. ZigZag Conversion

原题地址
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
解:

/*原理是通过计算获取到底部的序号和最上部的序号,即可以获取周围的信息了
 */
class Solution {
public:
    string convert(string s, int numRows) 
    {
       if (s.length() <= 1 || 1 == numRows) return s;
        vector<string> vec_str(numRows);
        int i = 0;
        for (int nPos = 0; nPos < s.length();++nPos)
        {
            int nBValue= (2*i+1)*(numRows-1);
            int nTValue= 2*i*(numRows-1);
            if (nPos == nBValue) 
                ++i;
            vec_str[abs(nTValue - nPos)] += s[nPos];
        }
        for (i = 1; i < numRows; ++i)
             vec_str[0] += vec_str[i];
        return vec_str[0];
    }
};

7. Reverse Integer

原题链接
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

解:

/*本道题比较精巧,花费了一点脑筋,先取余,再除10,如此循环即可得到最后一位,循环的同时还要再将余乘10,连续如此,即得到结果,还有一个重要的问题,要判断有无溢出,采用的方法是使用long来存结果,long与INT_MAX,INT_MIN来判断*/
class Solution {
public:
    int reverse(int x)
    {
        long nTotal =0;
        while (x)
        {
            nTotal = nTotal * 10 + x % 10;
            x /= 10;
        }
        return (nTotal > INT_MAX||nTotal < INT_MIN)? 0:nTotal; 
    }
};

8. String to Integer (atoi)

原题地址

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

解:

/*这个题直接举出遍历的各种情况就可以解决了,
但判断int的溢出我们可以使用一个较大类型来存,例long long,
再用来与INT_MAX判断即可*/
int myAtoi(char* str)
{
    long long nResult = 0;
    bool bNegative = false;
    for (;*str != '\0';str++)
    {
        if (*str == ' ')
            continue;
        if ((*str == '+' || *str == '-') && ('0' <= *(str + 1) && *(str + 1) <= '9'))
            bNegative= (*str == '+' )? false:true;
        if ((*str == '+' || *str == '-') && (*(str + 1) > '9' || *(str + 1) < '0'))
            return 0;
        if (('0' > *str || *str > '9') && *str != '+' && *str != '-')//不是数字,不是‘+’
            return 0;
        if ('0' <= *str && *str <= '9')
        {
            nResult *= 10;//先自*10,再加上该数字就好!
            nResult += (*str - '0');
            if (nResult>INT_MAX)
            {
                nResult = INT_MAX;
                if(bNegative)
                    nResult=INT_MIN;
                 return nResult;
            }
            if(('0' > *(str + 1) || *(str + 1)> '9'))
                break;
        }
    }
    if (bNegative)
        nResult = -nResult;
    return nResult;
}

9. Palindrome Number

原题地址

Determine whether an integer is a palindrome. Do this without extra space.

解:

/*共同的原理就是把这个数倒过来再来进过比对,如果两者的值相等就是一个回文,
定要成为这种方法的老司机!*/
//方法1:
    bool isPalindrome(int x) {
        int nTotal =0;
        int nValue=x;
        while (nValue>0)
        {
            nTotal = nTotal * 10 + nValue% 10;
            nValue /= 10;
        }
        return nTotal == x;
        }
方法2bool isPalindrome(int x) {
        if (x < 0) 
            return false;
        string str=to_string(x);
        string strTemp(str.rbegin(),str.rend());
        return str==strTemp;
        }

10.Regular Expression Matching

原题地址

Implement regular expression matching with support for ‘.’ and ‘*’.

‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:

isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true

解:

/*这个题比较难,难在情况多,较复杂,解决方法可以使用递归,也可以使用动态规划,动态规划这个要学习一下*/
bool isMatch(char* s, char* p) {

}

11. Container With Most Water

原题地址

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

解:

解法1/*这个题比较坑爹,但也算是一种思维的锻炼,解法1直接两个for,理论可行,但效率不高,慢的不要不要的*/
    int maxArea(vector<int>& height) 
    {
        int nMax = 0;
        for (int i = 0; i<height.size(); ++i)
        for (int j = i + 1; j<height.size(); ++j)
        {
            int nTemp = max(height[i], height[j])*abs(j - i+1);
            if (nTemp>nMax)
                nMax = nTe
        }
        return nMax;
    }
解法2/*这个题也是看网友的,没想到这么巧妙解决了
left和right都向中央移动,每次移动left和Right中间高度较小的(因为反正都是移动一次,宽度肯定缩小1,这时候只能指望高度增加来增加容量,肯定是替换掉高度较小的,才有可能找到更大的容量。)
这个解释比较正解!
*/
    int maxArea(vector<int>& height) 
    {
        int nL = 0;
        int nR = height.size() - 1;
        int nMax = 0;
        while(nL < nR)
        {
                int nTemp = (nR - nL)*min(height[nL], height[nR]);
                if (nTemp > nMax)
                    nMax = nTemp;
                height[nL] > height[nR]? nR-- : nL++;
        }
        return nMax;
    }

12. Integer to Roman

原题地址

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

解:

/*类似于一个map映射对应的罗马字符,还是老方法先除即获取了多少个该数字,再取余即对该数字剩下的余数再来*/
   string intToRoman(int num) 
    {
        int n[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        char* r[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

        string strResult;
        int nTemp=num,nTemp2 = 0;
        for (int i = 0; i < 13; ++i)
        {
            nTemp2 = nTemp / n[i];//控制循环次数
            while (nTemp2 > 0)
            {
                strResult += r[i];//添加进去
                --nTemp2;//控制退出
            }
            nTemp=nTemp%n[i];//取余,对每一项
        }
        return strResult;
    }

13. Roman to Integer

原题地址

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.
解:

/*
原理就是遍历字符串,遍历一次,再找char数组的相同项,
找到的话,就把对应的值计算出来,这里有一个判断,
先判断两个为一组的,再判断1个为组的。
*/
int romanToInt(string s) {
        int n[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        char* r[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
        int nResult=0;
        for(int nPos=0 ;nPos<s.size(); ++nPos)
           for(int j=0;j<13;++j)
           {
               if(strcmp(r[j],s.substr(nPos,2).c_str())==0)
               {
                   nPos+=1;
                   nResult+=n[j];
                   break;
               }
               else if(strcmp(r[j],s.substr(nPos,1).c_str())==0)
               {
                   nResult+=n[j];
                   break;
               }
           }
        return nResult;
    }

14. Longest Common Prefix

原题地址

Write a function to find the longest common prefix string amongst an array of strings.

解:

/*这道题比较简单,求数组内字符串的公共最长前缀,
直接遍历第一个串就可以了,再判断其它串某个位置值相同,相同长度就加1,最后返回substr*/
 string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()==0) return ""; 
        int nComLen=0;
        for(int nPos=0;nPos<strs[0].size();++nPos)
        {
            int nTemp=1;
            for( int j=1;j<strs.size();++j)
                if(strs[j][nPos] == strs[0][nPos]) 
                    ++nTemp;
                else
                    break ;
           if(nTemp==strs.size()) 
               ++nComLen;
           else 
               break;
        }
        return strs[0].substr(0,nComLen);

    }

15. 3Sum

原题地址

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

解:

vector<vector<int>> threeSum(vector<int>& nums) {

    }

16. 3Sum 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).

解:


17. Letter Combinations of a Phone Number

原题地址

Given a digit string, return all possible letter combinations that the number could represent.

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

A mapping of digit to letters (just like on the telephone buttons) is given below.

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

解:

 vector<string> letterCombinations(string digits) {
        char *pAry[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> vec_result,vec_temp;
        string strTemp;
        for (int i = 0;i<digits.size(); ++i)
        {
            int nNum = digits[i] - '0';//第几个,与前面所有的遍历
            vec_temp.clear();
            for (int j = 0; j < strlen(pAry[nNum]); ++j)
            {
                if (vec_result.size() == 0)
                {
                    strTemp="";
                    strTemp += pAry[nNum][j];
                    vec_temp.push_back(strTemp);
                }
                for (int k = 0; k<vec_result.size(); ++k)
                {
                    strTemp = "";
                    strTemp += vec_result[k];
                    strTemp += pAry[nNum][j];
                    vec_temp.push_back(strTemp);
                }
            }
            vec_result = vec_temp;
        }
        return vec_result;
    }
阅读更多
换一批

没有更多推荐了,返回首页