1. 程式人生 > 其它 >春節刷題day13:[LeetCode:面試題 05.07、02.01、08.03、01.02、17.04]

春節刷題day13:[LeetCode:面試題 05.07、02.01、08.03、01.02、17.04]

技術標籤:# LeetCode刷題指南c++

春節刷題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完結(年後上班第一天,太累了,完全不想動)。