LeetCode 2015.7.25 125,28,169,155,7,160,1

LeetCode 2015.7.25 125,28,169,155,7,160,1

125 Valid Palindrome
1.
class Solution {
public:
    bool isPalindrome(string s) {
        int flag[300]={0};
        for(char ch='a';ch<='z';ch++)
            flag[ch]=ch-'a'+1;
        for(char ch='A';ch<='Z';ch++)
            flag[ch]=ch-'A'+1;
        for(char ch='0';ch<='9';ch++)
            flag[ch]=ch-'0'+30;
        vector<int> num;
        num.clear();
        int lens=s.size();
        for(int i=0;i<lens;i++)
            if (flag[s[i]]>0) num.push_back(flag[s[i]]);
        int lenn=num.size()-1;
        for(int i=0,j=lenn;i<j;i++,j--)
            if (num[i]!=num[j]) return false;
        return true;

    }
};

2. LeetCode Solution
(1)用前后两个指针,如果是非字母直接过掉,是字母就都转换成小写,不同就返回false,相同就继续。
题解并没有像我一样先把字母提取出来并且转换,这个样子省掉了很多空间,以及少了一些循环。
(2)JAVA,自己改写成了C++
(3)isdigit()和isalpha()。头文件#include <ctype.h>
class Solution {
public:
    bool isPalindrome(string s) {
        int i=0, j= s.size()-1;
        while (i<j) {
            while (i<j && !isdigit(s[i]) && !isalpha(s[i])) i++;
            while (i<j && !isdigit(s[j]) && !isalpha(s[j])) j--;
            if (toupper(s[i])!=toupper(s[j]))
                return false;
            i++;
            j--;
        }
        return true;
    }
};


28 Implement strStr()
1.
class Solution {
public:
    int strStr(string haystack, string needle) {
        if (haystack.size()<needle.size()) return -1;
        int iend = haystack.size()-needle.size();
        for(int i=0;i<=iend;i++)
        {
            bool flag = true;
            for(int j=0;j<needle.size();j++)
            {
                if (needle[j]!=haystack[i+j])
                {
                    flag = false;
                    break;
                }
            }
            if (flag) return i;
        }
        return -1;
    }
};

2. LeetCode Solution
(1)拿到题目应该想到的问题
i. needle or haystack is empty. If needle is empty, always return 0. If haystack is empty, then there will always be no match (return –1) unless needle is also empty which 0 is returned.
ii. needle’s length is greater than haystack’s length. Should always return –1.
iii. needle is located at the end of haystack. For example, “aaaba” and “ba”. Catch possible off-by-one errors.
iv. needle occur multiple times in haystack. For example, “mississippi” and “issi”. It should return index 2 as the first match of “issi”.
v. Imagine two very long strings of equal lengths = n, haystack = “aaa…aa” and needle = “aaa…ab”. You should not do more than n character

(2)暴力枚举

(3)循环可以这样写: for(int i=0; ;i++)

(4)Code
class Solution {
public:
    int strStr(string haystack, string needle) {
        for(int i=0; ;i++){
            for(int j=0; ;j++){
                if (j == needle.size()) return i;
                if (i+j==haystack.size()) return -1;
                if (needle[j]!=haystack[i+j]) break;
            }
        }
    }
};

169 Majority Element
1.
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,int> appear;
        map<int,int>::iterator p;
        appear.clear();
        for(int i=0;i<nums.size();i++)
        {
            p=appear.find(nums[i]);
            if(p!=appear.end())
            {
                int tmp=p->second;
                tmp++;
                appear.erase(p);
                appear.insert(pair<int,int>(nums[i],tmp));
            }
            else
                appear.insert(pair<int,int>(nums[i],1));
        }
        int ans,num=-1;
        for(p=appear.begin();p!=appear.end();p++)
        {
            if (p->second > num)
            {
                num=p->second;
                ans=p->first;
            }
        }
        return ans;
    }
};

2. LeetCode Solution
给了好多个很不错的方法。
(1)Runtime: O(n2) — Brute force solution: Check each element if it is the majority element.
(2)Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.
(3)Runtime: O(n log n) — Sorting: As we know more than half of the array are elements of the same value, we can sort the array and all majority elements will be grouped into one contiguous chunk. Therefore, the middle (n/2th) element must also be the majority element.
(4)Average runtime: O(n), Worst case runtime: Infinity — Randomization: Randomly pick an element and check if it is the majority element. If it is not, do the random pick again until you find the majority element. As the probability to pick the majority element is greater than 1/2, the expected number of attempts is < 2.
(5)Runtime: O(n log n) — Divide and conquer: Divide the array into two halves, then find the majority element A in the first half and the majority element B in the second half. The global majority element must either be A or B. If A == B, then it automatically becomes the global majority element. If not, then both A and B are the candidates for the majority element, and it is suffice to check the count of occurrences for at most two candidates. The runtime complexity, T(n) = T(n/2) + 2n = O(n log n).
(6)Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
(7)Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.
(8)Update (2014/12/24): Improve algorithm on the O(n log n) sorting solution: We do not need to 'Find the longest contiguous identical element' after sorting, the n/2th element is always the majority.

155 Min Stack
1.
class MinStack {
public:
    void push(int x) {
        st.push(x);
        if (mi.empty() || x<=mi.top()) mi.push(x);
    }

    void pop() {
        int tmp=st.top();
        st.pop();
        if (tmp==mi.top()) mi.pop();
    }

    int top() {
        return st.top();
    }

    int getMin() {
        return mi.top();
    }

private:
    stack<int> st;
    stack<int> mi;

};

2. LeetCode Solution
Hints:
Consider space-time tradeoff. How would you keep track of the minimums using extra space?
Make sure to consider duplicate elements.

(1) O(n) runtime, O(n) space – Extra stack:
Use an extra stack to keep track of the current minimum value. During the push operation we choose the new element or the current minimum, whichever that is smaller to push onto the min stack.

(2) O(n) runtime, O(n) space – Minor space optimization:
If a new element is larger than the current minimum, we do not need to push it on to the min stack. When we perform the pop operation, check if the popped element is the same as the current minimum. If it is, pop it off the min stack too.

7 Reverse Integer
1.
class Solution {
public:
    int reverse(int x)
    {
        if (x==0) return 0;
        string str;
        str.clear();
        int positive;
        if (x>0) positive = 1;
        else
        {
            positive = -1;
            x=x*(-1);
        }
        int tmpmax=INT_MAX;
        string maxstr;
        maxstr.clear();
        while (tmpmax>0)
        {
            int p=tmpmax % 10;
            char ch=p+'0';
            maxstr=ch+maxstr;
            tmpmax/=10;
        }
        vector<int> ans;
        ans.clear();

        while (x>0)
        {
            int tmp = x % 10;
            ans.push_back(tmp);
            char ch=tmp+'0';
            str+=ch;
            x/=10;
        }
        if ((str.size()==maxstr.size())&&(str>maxstr)) return 0;
        int sum = 0;
        for(int i=0;i<ans.size();i++)
            sum=sum*10 + ans[i];
        return sum*positive;
    }
};



2. LeetCode Solution:
改写成了c++
class Solution {
public:
    int reverse(int x) {
        int ret = 0;
        int overflow = INT_MAX/10;
        while (x!=0) {
            if (abs(ret)>overflow)
                return 0;
            ret = ret * 10 + x % 10;
            x /= 10;
        }
        return ret;
    }
};

160 Intersection of Two Linked Lists
1. 两链表均不带环,若两链表相交,则必有相同的元素,且相交后的所有元素都相同,因此可以直接判断两链表的最后一个元素是否相等,若相等就相交(此方法应该效率最高)。若要求两链表相交处的元素,此方法的时间复杂组度为O(M+N).
若求两链表相交的第一个元素,如果确定两链表相交,设M>N,m,n为两链表的元素个数,则先将元素个数为M的链表向右移动M-N个元素,然后同时遍历两链表,如果M[I] = N[i],则i为第一个相交的元素

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* pA=headA;
        ListNode* pB=headB;
        if (pA==NULL || pB==NULL) return NULL;
        int numA=1,numB=1;
        while(pA->next!=NULL)
        {
            pA=pA->next;
            numA++;
        }
        while(pB->next!=NULL)
        {
            pB=pB->next;
            numB++;
        }
        if (pA!=pB) return NULL;
        if (numA<numB)
        {
            int tmp=numA;
            numA=numB;
            numB=tmp;
            pA=headB;
            pB=headA;
        }
        else
        {
            pA=headA;
            pB=headB;
        }
        for(int i=1;i<=numA-numB;i++)
        {
            pA=pA->next;
        }
        while(pA!=pB)
        {
            pA=pA->next;
            pB=pB->next;
        }
        return pA;
    }
};

2. LeetCode Solution
分析了多种方法,链表元素的地址也可以用来做哈希。

(1)Brute-force solution (O(mn) running time, O(1) memory):
For each node ai in list A, traverse the entire list B and check if any node in list B coincides with ai.

(2)Hashset solution (O(n+m) running time, O(n) or O(m) memory):
Traverse list A and store the address / reference to each node in a hash set. Then check every node bi in list B: if bi appears in the hash set, then bi is the intersection node.

(3)Two pointer solution (O(n+m) running time, O(1) memory):
Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A.
If at any point pA meets pB, then pA/pB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.

1 Two Sum
1.
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> pos,neg;
        vector<int> ans;
        int maxn = -INT_MAX;
        for(int i=0;i<nums.size();i++)
        {
            if (abs(nums[i])>maxn)
                maxn=abs(nums[i]);
        }
        maxn+=5;
        ans.clear();
        pos.clear();
        neg.clear();
        pos.resize(maxn);
        neg.resize(maxn);
        for(int i=0;i<nums.size();i++)
        {
            if (nums[i]>=0)
                pos[nums[i]]=i;
            else
                neg[abs(nums[i])]=i;
        }
        for(int i=0;i<nums.size();i++)
        {
            int tmp = target - nums[i];
            if (tmp>=0)
            {
                if (pos[tmp]>0)
                {
                    ans.push_back(i+1);
                    ans.push_back(pos[tmp]+1);
                    return ans;
                }
            }
            else
            {
                if (neg[abs(tmp)]>0)
                {
                    ans.push_back(i+1);
                    ans.push_back(neg[abs(tmp)]+1);
                    return ans;
                }
            }
        }
    }
};

2.
用的hashmap

(1) O(n2) runtime, O(1) space – Brute force:
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

(2) O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值