春节刷题day13:[LeetCode:面试题 05.07、02.01、08.03、01.02、17.04]

春节刷题day13:LeetCode

面试题 05.07. 配对交换

面试题 02.01. 移除重复节点

面试题 08.03. 魔术索引

面试题 01.02. 判定是否互为字符重排

面试题 17.04. 消失的数字


1、面试题 05.07. 配对交换

class Solution {
    
    
public:
    int exchangeBits(int num) {
    
    
        for(int i = 1; i < 31; i += 2){
    
    
            if((num & (1 << i)) && !(num & (1 << (i - 1)))){
    
    
                num ^= (1 << i); num |= (1 << (i - 1));
            }
            else if(!(num & (1 << i)) && (num & (1 << (i - 1)))){
    
    
                num |= (1 << i); num ^= (1 << (i - 1));
            }
        }
        return num;
    }
};

2、面试题 02.01. 移除重复节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* removeDuplicateNodes(ListNode* head) {
    
    
        unordered_set<int> vis;
        ListNode* HEAD = new ListNode(1);
        if(head == NULL) return HEAD -> next;
        HEAD -> next = head;
        ListNode* pre = HEAD;
        while(head){
    
    
            ListNode* r = head -> next;
            if(!vis.count(head -> val)){
    
    
                vis.insert(head -> val);
                pre = head; head = r;
            }else{
    
    
                pre -> next = r;
                head = r;
            }
        }
        return HEAD -> next;
    }
};

3、面试题 08.03. 魔术索引

//这一题并没有想到分治,等明天再回来补吧
class Solution {
    
    
public:
    int findMagicIndex(vector<int>& nums) {
    
    
        for(int i = 0; i < nums.size(); i++)
            if(nums[i] == i){
    
    
                return i;
            }
        return -1;
    }
};

4、面试题 01.02. 判定是否互为字符重排

class Solution {
    
    
public:
    bool CheckPermutation(string s1, string s2) {
    
    
        sort(s1.begin(), s1.end());
        sort(s2.begin(), s2.end());
        return s1 == s2;
    }
};
class Solution {
    
    
public:
    bool CheckPermutation(string s1, string s2) {
    
    
        unordered_map<int, int> pa;
        for(int i = 0; i < s1.size(); i++) pa[s1[i]]++;
        for(int i = 0; i < s2.size(); i++) pa[s2[i]]--;
        for(auto i : pa){
    
    
            if(i.second != 0) return false;
        }
        return true;
    }
};

5、面试题 17.04. 消失的数字

class Solution {
    
    
public:
    int missingNumber(vector<int>& nums) {
    
    
        long long sum = 0;
        for(long long i = 0; i <= nums.size(); i++) sum += i;
        for(int i = 0; i < nums.size(); i++) sum -= nums[i];
        return (int)sum;
    }
};

2021/2/18完结(年后上班第一天,太累了,完全不想动)。

猜你喜欢

转载自blog.csdn.net/shangzhengyu/article/details/113854653