LeetCode刷题笔记

2016/11/07
33. Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
My code:

    int search(vector<int>& nums, int target) {
        for(int i=0;iif(nums[i]==target)return i;
        }
        return -1;
    }

2016/11/07
80. Remove Duplicates from Sorted Array II
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
My code:

    int removeDuplicates(vector<int>& nums) {
            if (nums.size()<3)return nums.size();
            int num=nums[0];
            int len = nums.size();
            for(int i=2;iif(num==nums[i-2])
                {
                    len--;
                    nums.erase(nums.begin()+i);
                }
                else
                {
                    i++;
                }

            }
            return len;
    }

2016/11/07
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
My code:

    int removeDuplicates(vector<int>& nums) {
        if (nums.size()==0)return 0;
        if (nums.size()==1)return 1;
        int num=nums[0];
        int len = nums.size();
        for(int i=1;iif(num==nums[i-1])
            {
                len--;
                nums.erase(nums.begin()+i);
            }
            else
            {
                i++;
            }

        }
        return len;
    }

Use STL:

int removeDuplicates(vector<int>& nums) 
{
    return distance(nums.begin(), unique(nums.begin(), nums.end()));
}

Attention:
1,std::unique eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

2016/11/05
3. Longest Substring Without Repeating Characters
Examples:
Given “abcabcbb”, 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.
My code:

int lengthOfLongestSubstring(string s) {
    int max_lenth = 0;
    std::set<char> myset;
    for (int head = 0; head < s.size(); head++)
    {

        for (int tail = head; tailstd::max(max_lenth, int(myset.size()));
            if (myset.count(s[tail]))
            {
                myset.clear();
                break;
            }
            else
            {
                myset.insert(s[tail]);
                max_lenth = std::max(max_lenth, int(myset.size()));
            }

        }

    }
    return max_lenth;
}

可惜:Submission Result: Time Limit Exceeded

2016/11/01
2. Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Code:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *head = new ListNode(0);
    ListNode *tail = head;
    int c = 0;
    int s = 0;
    while (l1 || l2 || c != 0)
    {
        s = 0;
        if (l1) {
            s += l1->val;
            l1 = l1->next;
        }
        if (l2) {
            s += l2->val;
            l2 = l2->next;
        }
        s += c;
        c = s / 10;
        s = s % 10;

        ListNode *t = new ListNode(s);
        tail->next = t;
        tail = t;

    }
    return head->next;

}

2016/11/01
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.
Example:Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Code:
c++ code:

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        std::map<int,int> mapping;
        for(int i=0;ifor(int i=0;iint gap = target - nums[i];
            if(mapping.find(gap)!=mapping.end()&&mapping[gap]>i)
            {
                    result.push_back(i);
                    result.push_back(mapping[gap]);
            }

        }


        return result;

    }
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for i, num in enumerate(nums):
            if num in dic:
                return [dic[num], i]
            else:
                dic[target - num] = i

1,dict:有点匹配的意思,属于Mapping Types,{‘jack’: 4098, ‘sjoerd’: 4127}这个dict的key是string
2,定义一个新dict:new_dict={}或者new_dict=dict()
3,本代码的思想是遍历nums中的值,沿途把target-nums[i]的值存入另一个dict,当检测到某个nums中的值已经存在于dict中,那么这个值对应的indice与dict中记录下来的indice作为返回值。
4,对于C++的那一段,如果是在vector中查找gap那么会出现超出时间,在map中查找复杂度会降低。

2016/10/24
401. Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
Code:

    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        return ['%d:%02d' % (h, m)
            for h in range(12) for m in range(60)
            if (bin(h) + bin(m)).count('1') == num]

2016/10/24
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
My code:

    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        list0=list()
        for num in nums1:
            if num in nums2:
                list0.append(num)
                nums2.remove(num)
        return list0

注意:
1,list.insert(pos,item)需要两个参数,位置和值,list.append(item)只需要一个
2,list.remove(item)从list中删除一个item。

2016/10/24
217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
My code:
C++:

    bool containsDuplicate(vector<int>& nums) {
        std::unordered_set<int> s;
        for(int i:nums)
            if(s.find(i)==s.end())s.insert(i);
            else return true;
        return false;
    }

Python:

    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums)==1:
            return False
        s=set()
        for num in nums:
            if num in s:
                return True
            s.add(num)
        return False

注意:
1,if xxx: for xxx: 冒号都不要少
2,True,False是Python的bool类型,首字母大写
3,定义新的
set:s=set()
list:s1 = list()或者mylist = [],
dict:new_dict=dict() 或者new_dict={}
tuple:new_tuple=()

4,items in a list need not be of the same type

2016/10/16
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
1,use map

    int majorityElement(vector<int>& nums) {
        std::unordered_map<int,int> m;
        for(int i=0;iif(++m[nums[i]]>nums.size()/2)return nums[i];
    }

2,sorting

    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.begin()+nums.size());
        return nums[nums.size()/2];
    }
    or faster
    int majorityElement(vector<int>& nums) {
        nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
        return nums[nums.size() / 2];
    }

3,Randomization
amazing!!!

    int majorityElement(vector<int>& nums) {
        int n=nums.size();
        srand(unsigned(time(NULL)));
        while(1)
        {
            int candidate=nums[rand()%n];
            int count=0;
            for(int i=0;iif(candidate==nums[i])count++;
            if(count>n/2)return candidate;
        }
    }

2016/10/16
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
思路:第一次与最后一次出现的位置一样则是non-repeating
My code:

    int firstUniqChar(string s) {
        string r=s;
        for(int i=0;isize();i++)r[i]=s[s.size()-i-1];
        for(int j=0;jsize();j++)
        if(s.find(s[j],0)==(s.size()-r.find(s[j])-1))return j;
        return -1;
    }

2016/10/14
171. Excel Sheet Column Number
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3

Z -> 26
AA -> 27
AB -> 28
My code:

int titleToNumber(string s) {
    int num = s.size();
    int c=0;
    for(int k=0;k26 + s[k]-64;
    }
    return c;
}

注意:
1,string中的每一个都是char类型变量,例如char a=s[0];
2,ASCII表中A为65,a为97
3,查ASCII表时,Dec是十进制,Hx是16进制,Oct是八进制

2016/10/13
100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
My code:

    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL && q == NULL)return true;
        else
        {
            if(p!=NULL && q!= NULL)
            {
                if((p->val)==(q->val))return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
                else return false;
            }
            else
            {
                return false;
            }

        }
    }

注意:当node为NULL时不能进行node->val等操作,所以在进行访问前先判断node是否为NULL;

2016/10/13
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:Each element in the result must be unique.The result can be in any order.
My code:

    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> nums3;
        std::unordered_set<int> myset1;
        std::unordered_set<int> myset2;
        for(int n : nums1)myset1.insert(n);
        for(int m : nums2)myset2.insert(m);
        //int size=(myset1.size()
        for(int k:myset1)
        {
            std::unordered_set<int>::const_iterator got = myset2.find (k);
            if ( got != myset2.end() )nums3.push_back(k);
        }
        return nums3;
    }

2016/10/13
237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
题目的意思是输入的节点就是你想删除的节点。
My code:

    void deleteNode(ListNode* node) {
        if(node->next!=NULL)
        {
            node->val=node->next->val;
            node->next=node->next->next;
            //node=node->next;
        }

不过不太明白为何注释掉的那一行为何不行。
(10分钟后),注释那一行应该是 *node = *node->next;因为这个函数是void的,只能通过对原数据块操作才能有效,如果是node=node->next的话node指针的值是不会传回的,这个函数等价于

ListNode* deleteNode(ListNode* node)
{
    node=node->next;
    return node;
}

2016/10/13
409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
Input: “abccccdd” ,Output:7,Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
思路:问题可以转化为:找到字符串中有多少个不能配对的字符,也就是把相同的两个字母捆一起找出剩下的个数。
My code 1:效率非常低,双重循环。
My code 2:利用c++的set容器,从350ms降低至22ms

    int longestPalindrome(string s) {
    std::unordered_set<char> myset;

    for(int i=0;istd::unordered_set<char>::const_iterator got = myset.find (s[i]);
        if ( got == myset.end() )myset.insert(s[i]);
        else myset.erase(s[i]);
    }
        return myset.size()==0?(s.size()):(s.size()-(myset.size()-1));
    }

2016/10/13
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.

    int sumOfLeftLeaves(TreeNode* root) {
        int sum=0;
        if(root->left == NULL)
        {
            return root->val;
        }
        else
        {
            sum=sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
        }

    }

2016/10/11
283. Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Code:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int left = 0;
        for(auto & e : nums) if(e!=0) swap(e,nums[left++]);
    }
};

细节:
1,i++是先赋值,再加一
2,swap(a,b)理解为ab值交换
3,程序里的left是左边left个数为原数组中前left个非零数,本质是之后数组第i个数是之前数组第i个非零数。left++就是用来计这个数的

2016/10/08
226. Invert Binary Tree
思路:递归的本质是迭代到终止条件,迭代过程必须完美阐述每一层之间的转换关系。
My code:

TreeNode* invertTree(TreeNode* root) {
    TreeNode* invert=root;
    if(invert!=NULL)
    {
        TreeNode* tmp;
        tmp = invert->left;
        invert->left  = invert->right;
        invert->right = tmp;

        invert->left = invertTree(invert->left);
        invert->right = invertTree(invert->right);
    }
    return invert;
}

2016/10/08
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.String t is generated by random shuffling string s and then add one more letter at a random position.Find the letter that was added in t.
思路:和136. Single Number一样。
My code:

    char findTheDifference(string s, string t) {
        vector<char> sum;
        int result=0;
        for(int i=0;ifor(int j=0;jfor(int k=0;kreturn result;
    }

2016/10/08
258. Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.For example:Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
利用递归:一行足矣

    int addDigits(int num) {
        return num<10?num:addDigits(num/1000000000+num%1000000000/100000000+num%100000000/10000000+num%10000000/1000000+num%1000000/100000+num%100000/10000+num%10000/1000+num%1000/100+num%100/10+num%10);
    }

2016/10/08
104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
利用递归,树的最大深度等于他子树最大深度加一。
Code:

    int maxDepth(TreeNode* root) {
        return root==NULL?0:max(maxDepth(root->left),maxDepth(root->right))+1;
    }

2016/10/07
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.Example:Given a = 1 and b = 2, return 3.
code:

class Solution {
public:
    int getSum(int a, int b) {
        int sum=0;
        while(b!=0)//carry==0
        {
            sum=a^b;//sum without carry
            b=(a&b)<<1;//carry
            a=sum;//sum without carry+carry
        }
        return sum;
    }
};

2016/10/07
292. Nim Game
思路:通过观察第5和6个发现,要想推倒第n个石头,那么第n-4块石头必须由你推倒,而且是你那次推倒的最后一块石头。以此类推,n=4,8,12…时候你是赢不了的,所以:
best code:

class Solution {
public:
    bool canWinNim(int n) {
        return n%4!=0;
    }
};

2016/10/07
344. Reverse String
Write a function that takes a string as input and returns the string reversed. Example: Given s = “hello”, return “olleh”.
复习小细节:
1,string字符数:s.size();与vector一致。
2,c++取余数:10%3=1。
3,交换数据:tmp=a;a=b;b=tmp;
My code:

class Solution {
public:
    string reverseString(string s) {
        for(int i=0;i2;i++)
        {
            char tmp = s[i];//h
            s[i] = s[s.size()-i-1];//o
            s[s.size()-i-1]=tmp;//h
        }
        return s;
    }
};

2016/10/06
136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
My code:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        for(int i=0;i1;i++)
        {
            int a=nums[i];
            bool isRepeat = false;
            for(int j=i+1;jif(a==nums[j])
                {
                    isRepeat= true;
                    break;
                }
            }
            if(isRepeat==false)
            {
                return nums[i];
            }
        }
        return nums[nums.size()-1];
    }
};

我写的这段代码并不符合linear runtime complexity这个要求,容我再想想。复习小细节:
1,退出for循环用break;
2,数组大小用vector.size();

最佳答案:

int singleNumber(int A[], int n) {
    int result = 0;
    for (int i = 0; ireturn result;
}

利用按位抑或XOR的可交换性即0^A^B^A=0^A^A^B=0^0^B=B。

你可能感兴趣的:(小总结)