0281-0290

281. Zigzag Iterator $\star\star$

282. Expression Add Operators $\star\star\star$

283. Move Zeroes $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  void moveZeroes(vector<int>& nums) {
    int j = 0;
    for (int num : nums)
      if (num != 0) nums[j++] = num;

    for (int i = j; i < nums.size(); ++i) nums[i] = 0;
  }
};

284. Peeking Iterator $\star\star$

285. Inorder Successor in BST $\star\star$

286. Walls and Gates $\star\star$

287. Find the Duplicate Number $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int findDuplicate(vector<int>& nums) {
    int slow = nums[nums[0]];
    int fast = nums[nums[nums[0]]];

    while (slow != fast) {
      slow = nums[slow];
      fast = nums[nums[fast]];
    }

    slow = nums[0];

    while (slow != fast) {
      slow = nums[slow];
      fast = nums[fast];
    }

    return slow;
  }
};

288. Unique Word Abbreviation $\star\star$

289. Game of Life $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  void gameOfLife(vector<vector<int>>& board) {
    const int m = board.size();
    const int n = board[0].size();

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        int ones = 0;
        for (int y = max(0, i - 1); y < min(m, i + 2); ++y)
          for (int x = max(0, j - 1); x < min(n, j + 2); ++x)
            ones += board[y][x] & 1;
        if ((board[i][j] == 1 && (ones == 3 || ones == 4)) ||
            (board[i][j] == 0 && ones == 3))
          board[i][j] |= 0b10;
      }

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) board[i][j] >>= 1;
  }
};

290. Word Pattern $\star$