Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- O(n) solution
- class Solution {
- public:
- int chalkReplacer(vector<int>& chalk, int k) {
- k %= accumulate(begin(chalk), end(chalk), 0l);
- for(int i = 0; i < chalk.size(); ++i)
- if((k -= chalk[i]) < 0)
- return i;
- return 0;
- }
- };
- -----------
- O(n) solution
- class Solution {
- public:
- int chalkReplacer(vector<int>& c, int k) {
- long long n = c.size();
- vector<long long> chalk(n);
- chalk[0] = c[0];
- for(int i=1; i<chalk.size(); i++)
- chalk[i] = chalk[i-1]+c[i];
- k = k%chalk[n-1];
- if(k == 0) return 0;
- int pos = upper_bound(chalk.begin(), chalk.end(), k)-chalk.begin();
- return pos;
- }
- };
Add Comment
Please, Sign In to add comment