LeetCode 第 183 场周赛

LeetCode 第 183 场周赛

  1. 非递增顺序的最小子序列

降序排列后,往 vector<int>ans 中添加元素,直到其和超过所有元素和的一半。

class Solution {
 public:
  vector<int> minSubsequence(vector<int>& nums) {
    const int n = nums.size();
    sort(nums.begin(), nums.end(), greater<int>());
    int s = accumulate(nums.begin(), nums.end(), 0);
    int ps = 0;
    vector<int>ans;
    for(int i = 0; i < n; ++i) {
      ps += nums[i];
      ans.push_back(nums[i]);
      if(ps > s - ps)
        return ans;
    }
    return ans;
  }
};
  1. 将二进制表示减到 1 的步骤数

注意有500位,暴力模拟即可。

class Solution {
 public:
  int numSteps(string s) {
    int ans(0);
    while(s != "1") {
      ans ++;
      const int n = s.length();
      cout << s  << endl;
      if(s[n - 1] == '0') {
        s.erase(s.end() - 1);
      } else if(s.find_last_of("0") != string::npos) {
        s[s.find_last_of("0")] = '1';
      } else {
        s = "1";
        for(int i = 0; i < n; ++i)
          s += "0";
      }

    }
    return ans;
  }
};
  1. 最长快乐字符串

优先加剩余数目多的,能加则加,不能则选次多的,直到不能再加。

class Solution {
 public:
  string longestDiverseString(int a, int b, int c) {
    pair<int, char> q[3] = {{a, 'a'}, {b, 'b'}, {c, 'c'}};
    string s("");
    for(int n;;) {
      sort(q, q + 3, greater<pair<int, char> >());
      if(q[0].first == 0)
        break;
      n = s.length();
      if(n >= 2 && q[0].second == s[n - 1] && q[0].second == s[n - 2]) {
        if(q[1].first == 0)
          return s;
        else {
          s += q[1].second;
          q[1].first --;
        }
      } else {
        s += q[0].second;
        q[0].first --;
      }
    }
    return s;
  }
};
  1. 石子游戏 III
    dp[i] 表示从 i 开始先手的最优情况,dp[i].first 是先手的值,dp[i].second 是后手的值。
    从后往前以先手最佳策略推
    当前选手的最佳结果等于所有可能取法中(取1、2 还是 3 个)的最佳结果,假定取的是 i 到 j ,那么就依赖 d[j+1] 的状态(先后手交换)。
class Solution {
 public:
  string stoneGameIII(vector<int>& stoneValue) {
    const int n = stoneValue.size();
    vector<pair<int, int> >d(n, {0, 0});
    for(int i = n - 1; i >= 0; --i) {
      d[i] = make_pair(INT_MIN, INT_MIN);
      for(int j = i; j < n && j < i + 3; ++j) {
        int rs = accumulate(&stoneValue[i], &stoneValue[j + 1], 0);
        if(j + 1 < n)
          d[i] = max(make_pair(d[j + 1].second + rs, d[j + 1].first), d[i]);
        else
          d[i] = max(make_pair(rs, 0), d[i]);
      }
      //cout << i << " " << d[i].first << " " << d[i].second << endl;
    }
    int sum = accumulate(stoneValue.begin(), stoneValue.end(), 0);
    return sum - d[0].first != d[0].first ? (sum - d[0].first > d[0].first ? "Bob" : "Alice") : "Tie";

  }
};

猜你喜欢

转载自www.cnblogs.com/Forgenvueory/p/12636674.html