0561-0570

561. Array Partition I $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int arrayPairSum(vector<int>& nums) {
    int ans = 0;

    sort(nums.begin(), nums.end());
    for (int i = 0; i < nums.size(); i += 2) ans += nums[i];

    return ans;
  }
};

562. Longest Line of Consecutive One in Matrix $\star\star$

563. Binary Tree Tilt $\star$

564. Find the Closest Palindrome $\star\star\star$

565. Array Nesting $\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 arrayNesting(vector<int>& nums) {
    int ans = 0;

    for (int num : nums) {
      if (num == -1) continue;
      int index = num;
      int count = 0;
      while (nums[index] != -1) {
        int temp = index;
        index = nums[index];
        nums[temp] = -1;
        ++count;
      }
      ans = max(ans, count);
    }

    return ans;
  }
};

566. Reshape the Matrix $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
    if (nums.empty() || r * c != nums.size() * nums[0].size()) return nums;

    vector<vector<int>> ans(r, vector<int>(c));
    int k = 0;

    for (vector<int>& row : nums)
      for (int num : row) {
        ans[k / c][k % c] = num;
        ++k;
      }

    return ans;
  }
};

567. Permutation in String $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  bool checkInclusion(string s1, string s2) {
    const int m = s1.length();
    const int n = s2.length();

    vector<int> map1(26);
    vector<int> map2(26);

    for (char c : s1) ++map1[c - 'a'];

    for (int i = 0; i < n; ++i) {
      if (i >= m) --map2[s2[i - m] - 'a'];
      ++map2[s2[i] - 'a'];
      if (map1 == map2) return true;
    }

    return false;
  }
};

568. Maximum Vacation Days $\star\star\star$

569. Median Employee Salary $\star\star\star$

570. Managers with at Least 5 Direct Reports $\star\star$