leetcode 中等题(1)

 

2. Add Two Numbers(中等)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* first = l1;
        ListNode* second = l2;
        int result1=0,result2=0;
        long long result=0;
        stack<int> S;
        int count=0;
        
        while(l1 != NULL){
            S.push(l1->val);
            l1 = l1->next;
        }
            
            
        count = S.size()-1;
        while(!S.empty()){
            result1 += pow(10,count--) * S.top();
            S.pop();
        }
            
        
        while(l2 != NULL){
            S.push(l2->val);
            l2 = l2->next;
        }
            
        count = S.size()-1;
        while(!S.empty()){
            result2 += pow(10,count--) * S.top();
            S.pop();
        }
            
        result = result1 + result2;
        delete first,second;
        
        // ListNode*p = new ListNode(-1);  //头节点
        ListNode* pHead = NULL;
        ListNode* p = pHead;
        
        if(!result){
            ListNode* q = new ListNode(0);
            pHead = q;
        }
        while(result){
            int val = result % 10;
            result /= 10;
            
            ListNode* q = new ListNode(val);
            if(pHead == NULL){
                pHead = q;
                p = q;
            }
            else{
                p->next = q;
                p = p->next;
            }
        }
        return pHead;
    }
};
此方法会溢出,超过long long 型范围
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {   //正确解法,按位相加,注意进位
    ListNode *head = NULL, *prev = NULL;
    int carry = 0;
    while (l1 || l2) {
        int v1 = l1? l1->val: 0;
        int v2 = l2? l2->val: 0;
        int tmp = v1 + v2 + carry;
        carry = tmp / 10;
        int val = tmp % 10;
        ListNode* cur = new ListNode(val);
        if (!head) head = cur;
        if (prev) prev->next = cur;
        prev = cur;
        l1 = l1? l1->next: NULL;
        l2 = l2? l2->next: NULL;
    }
    if (carry > 0) {
        ListNode* l = new ListNode(carry);
        prev->next = l;
    }
    return head;
}

 3, Longest Substring Without Repeating Characters.(很慢)

int lengthOfLongestSubstring(string s) {

    int maxLength = 0;
    int count;
    for(int i=0;i<s.length();i++){
        string currString = "";
        count = 0;
        for(int j=i;j<s.length();j++){
            if(currString.find(s[j])>=currString.length()){
                currString += s[j];
                count++;
                cout<<s[j]<<endl;
                cout<<"string:"<<currString<<endl; 
                if(count>maxLength) maxLength = count;
            } 
            else{
                break;
            }
        }
    }
    return maxLength;
}

5, Longest Palindromic Substring.(很慢)

string longestPalindrome(string s) {
    string maxString = "";
    int maxLength = 0;
    int count = 0;
        
    for(int i=0;i<s.length();i++){
        string Str = "";
        int index = s.rfind(s[i]);
        int start = i;
        int end = index;
        int count = 0;
        int ii=start;
            
        while(ii<=index){
            if(s[ii]==s[index]){ii++;index--;}
            else{
                ii = start;
                index = end-1;
                end--;
            }   //匹配失败
        }
            
        if(ii>index){  //匹配成功
            for(int k=start;k<=end;k++)
                Str += s[k];
            count = Str.length();
        }
        if(count>=maxLength) {maxString = Str;maxLength=count;}
    }
    return maxString;
}

 8. String to Integer (atoi)(中等,参考)

int myAtoi(string str) {
    long result = 0;
    int indicator = 1;
    for(int i = 0; i<str.size();)
    {
        i = str.find_first_not_of(' ');
        if(str[i] == '-' || str[i] == '+')
            indicator = (str[i++] == '-')? -1 : 1;
        while('0'<= str[i] && str[i] <= '9') 
        {
            result = result*10 + (str[i++]-'0');
            if(result*indicator >= INT_MAX) return INT_MAX;
            if(result*indicator <= INT_MIN) return INT_MIN;                
        }
        return result*indicator;
    }
    return 0;
}

 15,3Sum(中等)

    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int sum;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++){
            if(i>0 && nums[i]==nums[i-1])
                continue;
            int l=i+1;
            int r=nums.size()-1;

            while(l<r){
                sum = nums[i]+nums[l]+nums[r];
                if(sum<0) l++;
                else if(sum>0) r--;
                else{
                    res.push_back(vector<int>{nums[i],nums[l],nums[r]});
                    while(nums[l]==nums[l+1]) l++;   //去除重复
                    while(nums[r]==nums[r-1]) r--;
                    l++;
                    r--;
                }
            }
            
        }
        return res;
    }

 11. Container With Most Water(很慢)

    int maxArea(vector<int>& height) {
        int maxAreas=0;
        int currAreas=0;
        for(int i=0;i<height.size();i++){
            for(int j=i+1;j<height.size();j++){
                currAreas = (j-i)*min(height[i],height[j]);
                if(currAreas>maxAreas) maxAreas = currAreas;
            }
        }
        return maxAreas;
    }

 12. Integer to Roman(中等)

    string intToRoman(int num) {
        const string THOUS[]={"","M","MM","MMM"};
        const string HUNDS[]=              {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        const string TENS[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        const string ONES[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};
        
        string result = "";
        result += THOUS[num/1000]; num %= 1000;
        result += HUNDS[num/100]; num %= 100;
        result += TENS[num/10]; num %= 10;
        result += ONES[num%10];
        
        return result;
    }

 16. 3Sum Closest(较快)

    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int minDist=INT_MAX;
        int res=0;
        for(int i=0;i<nums.size();i++){
            int l=i+1;
            int r=nums.size()-1;
            while(l<r){
                int sum = nums[i]+nums[r]+nums[l];
                if(sum==target) return sum;
                if(abs(sum-target)<minDist) {res=sum;minDist=abs(sum-target);}
                if(sum>target) r--;
                else l++;
            }//while
        }
        return res;
    }
};

 17. Letter Combinations of a Phone Number(较快)

    vector<string> letterCombinations(string digits) {
        if(digits.empty()) return vector<string>();
        vector<string> result;
        result.push_back("");
        vector<string> src = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for(int i=0;i<digits.size();i++){
            int num = digits[i]-'0';
            if(num<0 || num>9) break;
            const string& candidate = src[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;
    }

 19. Remove Nth Node From End of List(中等)

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == NULL) return NULL;
        ListNode* after=head;
        ListNode* befor=head;
        ListNode* toBeDelete;
        
        
        for(int i=0;i<n;i++){
            befor = befor->next;
            if(befor==NULL) return head->next;
        }
            
        while(befor->next!=NULL){
            befor = befor->next;
            after = after->next;
        }
        
        toBeDelete = after->next;
        after->next = toBeDelete->next;
        delete toBeDelete;
        toBeDelete = NULL;
        
        return head;
    }

 22. Generate Parentheses(中等)

    vector<string> res;
    void helper(string str,int left,int right){
        if(left==0 && right==0) res.push_back(str);
        if(left!=0) helper(str+'(',left-1,right);
        if(right!=0 && right>left) helper(str+')',left,right-1);
    }
    
    vector<string> generateParenthesis(int n) {
        helper("",n,n);
        return res;
    }

 24. Swap Nodes in Pairs(较快)

    ListNode* swapPairs(ListNode* head) {
        if(head==NULL) return NULL;
        ListNode tmp(0);
        ListNode* curr=head;
        ListNode* pre=&tmp;
        tmp.next=head;

        while(curr && curr->next){
            pre->next=curr->next;
            pre=pre->next;
            curr->next=pre->next;
            pre->next=curr;
            pre=curr;
            curr=curr->next;
        }
        return tmp.next;
    }

 

posted on 2018-12-29 21:48  爱笑的张飞  阅读(354)  评论(0编辑  收藏  举报

导航