Analysis of Leetcode Problem Solving Ideas (28) 200-206

  1. Number of Islands
    Give you a two-dimensional grid composed of '1' (land) and '0' (water). Please count the number of islands in the grid.
    Islands are always surrounded by water, and each island can only be formed by connecting adjacent land in the horizontal or vertical direction.

This problem can be solved with BFS or DFS

class Solution {
    
    
private:
    void dfs(vector<vector<char>>& grid, int r, int c) {
    
    
        int nr = grid.size();
        int nc = grid[0].size();

        grid[r][c] = '0';
        if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(grid, r - 1, c);
        if (r + 1 < nr && grid[r+1][c] == '1') dfs(grid, r + 1, c);
        if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c - 1);
        if (c + 1 < nc && grid[r][c+1] == '1') dfs(grid, r, c + 1);
    }

public:
    int numIslands(vector<vector<char>>& grid) {
    
    
        int nr = grid.size();
        if (!nr) return 0;
        int nc = grid[0].size();

        int num_islands = 0;
        for (int r = 0; r < nr; ++r) {
    
    
            for (int c = 0; c < nc; ++c) {
    
    
                if (grid[r][c] == '1') {
    
    
                    ++num_islands;
                    dfs(grid, r, c);
                }
            }
        }

        return num_islands;
    }
};

class Solution {
    
    
public:
    int numIslands(vector<vector<char>>& grid) {
    
    
        int nr = grid.size();
        if (!nr) return 0;
        int nc = grid[0].size();

        int num_islands = 0;
        for (int r = 0; r < nr; ++r) {
    
    
            for (int c = 0; c < nc; ++c) {
    
    
                if (grid[r][c] == '1') {
    
    
                    ++num_islands;
                    grid[r][c] = '0';
                    queue<pair<int, int>> neighbors;
                    neighbors.push({
    
    r, c});
                    while (!neighbors.empty()) {
    
    
                        auto rc = neighbors.front();
                        neighbors.pop();
                        int row = rc.first, col = rc.second;
                        if (row - 1 >= 0 && grid[row-1][col] == '1') {
    
    
                            neighbors.push({
    
    row-1, col});
                            grid[row-1][col] = '0';
                        }
                        if (row + 1 < nr && grid[row+1][col] == '1') {
    
    
                            neighbors.push({
    
    row+1, col});
                            grid[row+1][col] = '0';
                        }
                        if (col - 1 >= 0 && grid[row][col-1] == '1') {
    
    
                            neighbors.push({
    
    row, col-1});
                            grid[row][col-1] = '0';
                        }
                        if (col + 1 < nc && grid[row][col+1] == '1') {
    
    
                            neighbors.push({
    
    row, col+1});
                            grid[row][col+1] = '0';
                        }
                    }
                }
            }
        }

        return num_islands;
    }
};
  1. Number range bitwise AND
    Given range [m, n], where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range (including m, n end points).

The essence of this question is how to simplify the number of bit operations. First of all, we should pay attention to the smaller number. If the number of digits is different, just start from the decimal. Second, when the digits are the same, find the different digits and assign the value 0


class Solution {
    
    
public:
    int rangeBitwiseAnd(int m, int n) {
    
    
        if (m == n || m == 0) {
    
    
            return m;
        } else if (floor(log(n)/log(2)) - floor(log(m)/log(2)) >= 1) {
    
    
            return 0;
        } else {
    
    
            int xorResult = n ^ m;
            int bits = floor(log(xorResult)/log(2)) + 1;
            return (m >> bits) << bits;
        }
    }
};


  1. Happy number
    Write an algorithm to determine whether a number n is a happy number.
    "Happy number" is defined as: For a positive integer, every time the number is replaced by the sum of the squares of the numbers in each position, and then this process is repeated until the number becomes 1, or it may be an infinite loop but it never changes. To 1. If it can be changed to 1, then this number is a happy number.

This question involves the possibility of loops, so it is better to use fast and slow pointers to detect loops

class Solution {
    
    
public:
    int bitSquareSum(int n) {
    
    
        int sum = 0;
        while(n > 0)
        {
    
    
            int bit = n % 10;
            sum += bit * bit;
            n = n / 10;
        }
        return sum;
    }
    
    bool isHappy(int n) {
    
    
        int slow = n, fast = n;
        do{
    
    
            slow = bitSquareSum(slow);
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
        }while(slow != fast);
        
        return slow == 1;
    }
};



  1. Remove linked list elements
    Delete all nodes in the linked list that are equal to the given value val.
class Solution {
    
    
  public:
  ListNode* removeElements(ListNode* head, int val) {
    
    
    ListNode* sentinel = new ListNode(0);
    sentinel->next = head;

    ListNode *prev = sentinel, *curr = head, *toDelete = nullptr;
    while (curr != nullptr) {
    
    
      if (curr->val == val) {
    
    
        prev->next = curr->next;
        toDelete = curr;
      } else prev = curr;

      curr = curr->next;

      if (toDelete != nullptr) {
    
    
        delete toDelete;
        toDelete = nullptr;
      }
    }

    ListNode *ret = sentinel->next;
    delete sentinel;
    return ret;
  }
};


  1. Counting prime numbers Count the number of
    all prime numbers less than a non-negative integer n.

Using the Eradosé sieve method: first set all to prime numbers, and then exclude their multiples in turn

class Solution {
    
    
public:
    int countPrimes(int n) {
    
    
        int count = 0;
        //初始默认所有数为质数
        vector<bool> signs(n, true);
        for (int i = 2; i < n; i++) {
    
    
            if (signs[i]) {
    
    
                count++;
                for (int j = i + i; j < n; j += i) {
    
    
                    //排除不是质数的数
                    signs[j] = false;
                }
            }
        }
        return count;
    }
};
  1. Isomorphic strings
    Given two strings s and t, judge whether they are isomorphic.
    If the characters in s can be replaced to get t, then the two strings are isomorphic.
    All occurrences of characters must be replaced with another character while preserving the order of the characters. Two characters cannot be mapped to the same character, but the character can be mapped to itself.

There are two methods for this question: use a map to map the existing characters, and then check each time whether the mapping is the same. The second method is to convert the characters to numbers, and then compare the two strings of numbers

class Solution {
    
    
public:
    bool isIsomorphic(string s, string t) 
    {
    
    
        if (s.empty() && t.empty())
            return true;
        
        for(int i = 0; i < s.size(); i++)
        {
    
    
            if( s.find(s[i]) != t.find(t[i])) 
            return false;
        }
        return true;       
    }
};


  1. Reverse Linked List
    Reverse a singly linked list.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        ListNode *next, *ptr, *prev;
        ptr = next = head;
        prev = NULL;
        while (ptr)
        {
    
    
            next = ptr->next;
            ptr->next = prev;
            prev = ptr;
            ptr = next;
        }
        return prev;
    }
};

class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if (head == NULL || head->next == NULL) {
    
    
            return head;
        }
        ListNode* ret = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/u013354486/article/details/106470158