LeetCode第一天

1、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.

递归求和,注意得到位不同,和位相同(这个要进位,<<1)。

class Solution {
public:
    int getSum(int a, int b) {
        if(a==0)
        {
            return b;
        }
        else if(b==0)
        {
            return a;
        }
        else
        {
            return getSum(a^b,(a&b)<<1);
        }
    }
};

2、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.

递归求法,往上+1。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
       if(root)
       {
           return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
       }
       else
       {
           return 0;
       }
    }
};

3、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.
除去各种特殊情况,然后递归。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==nullptr&&q==nullptr)
        {
            return true;
        }
        else if((p==nullptr&&q!=nullptr)||(p!=nullptr&&q==nullptr))
        {
            return false;
        }
        else if(p->val==q->val)
        {
            return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
        }
        else
        {
            return false;
        }
    }
};

4、Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.
排列嘛,各个字符出现次数肯定相同。

class Solution {
public:
    bool isAnagram(string s, string t) {
        //t is an anagram of s
        int a[26]{},b[26]{};
        for(const char &c:s)
        {
            ++a[c-'a'];
        }
        for(const char &c:t)
        {
            ++b[c-'a'];
        }
        for(int i=0;i<26;++i)
        {
            if(a[i]!=b[i])
            {
                return false;
            }
        }
        return true;

    }
};

5、Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?
判断形参中几位1,形参位与该数0x55555555(4的power分布)结果中几位1。

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num>0)
        {
            bitset<32> bitvec(num),bitvec2(num&0x55555555);
            if(bitvec.count()==1&&bitvec2.count()==1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
};

6、Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
注意头结点,和结束条件,其实else里面一个可以归于结束条件中。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        for(ListNode *p=head;p&&p->next!=nullptr;)
        {
            if(p==head)
            {
                ListNode *temp=p->next;
                p->next=temp->next;
                head=temp;
                temp->next=p;
            }
            else if(!p->next->next)
            {
                break;
            }
            else
            {
                 ListNode *temp=p->next,*temp2=temp->next;
                 temp->next=temp2->next;
                 p->next=temp2;
                 temp2->next=temp;
                 p=temp;
            }
        }
        return head;
    }
};

7、Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.
元音判断的字符串,索引数组生成,而后逆序即可。

class Solution {
public:
    string reverseVowels(string s) {
       string vowels("aeiouAEIOU");
       vector<int> vPos;
       for(int i=0;i<s.length();++i)
       {
           if(vowels.find(s[i])!=-1)
           {
               vPos.push_back(i);
           }
       }
       int i=vPos.size()-1;
       string str(s);
       for(int j=0;j<s.length();++j)
       {
           if(vowels.find(str[j])!=-1)
           {
               str[j]=s[vPos[i--]];
           }
       }
       return str;
    }
};

8、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].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
辅助数组的构建,用于标识。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        int len=nums2.size();
        vector<int> vr,nums2Log(len,0);
        for(auto iter=nums1.begin();iter!=nums1.end();++iter)
        {
            for(int i=0;i<len;++i)
            {
                if((!nums2Log[i])&&(*iter==nums2[i]))
                {
                    vr.push_back(*iter);
                    nums2Log[i]=1;
                    break;
                }
            }
        }
        return vr;
    }
};

9、总结:
题目短小,其实都是可以大做文章。下面是一些新学到的公式。
A、数根
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.
实际上这个根据十进制展开,38=3*10+8,得到(3+8)mod 9。

class Solution {
public:
    int addDigits(int num) {
        return num-9*((num-1)/9);//求余数
    }
};

B、Nim Game
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

对于一个Nim游戏的局面(a1,a2,…,an),它是P-position当且仅当a1^a2^…^an=0,其中^表示异或(xor)运算。P-position表示先手赢。
1(1)、2(1)、3(1)、4(0)、5(1)、6(1)、7(1)、8(0)…….其中1表示true,0表示false。

class Solution {
public:
    bool canWinNim(int n) {
        return n%4!=0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值