intcheckWhere(int n, string &s1, int len1, string &s2, int len2){ for (int i = 0; i < len2; i++) { int n_target = n + len1; bool found = false; for (; n < n_target; n++) { if (s1[n % len1] == s2[i]) { n++; found = true; break; } } if (!found) { return-1; } } return n; }
classSolution { public: intcheckWhere(int n, string &s1, int len1, string &s2, int len2, map<int, pair<int, int>>& memo){ for (int i = 0; i < len2; i++) { int n_target = n + len1; bool found = false; for (; n < n_target; n++) { if (s1[n % len1] == s2[i]) { n++; found = true; break; } } if (!found) { return-1; } } return n; }
intgetMaxRepetitions(string s1, int n1, string s2, int n2){ map<int, pair<int, int>> memo; int now_n = 0; // from the nth letter of s1, to which will have one s2 int len1 = s1.size(), len2 = s2.size(); int max_n = len1 * n1; int now_num_s2 = 0; int n, temp; while (now_n < max_n) { n = now_n % len1; if (memo.find(n) != memo.end()) { // now already found // 之前用了now_n这么多个,也就是用了now_n//len1这么多个s1,并且找到了now_num_s2这么多个s2 // 现在需要做什么?现在需要跳回到data[n][0]这个位置,并且可以得到now_num_s2 - memo[n][1]这么多个s2 // 需要用到多少s1呢? int need_n = n / len1 * len1 + memo[n].first; while (need_n % len1 != n) { need_n = need_n / len1 * len1 + memo[need_n % len1].first; } // 现在到了need_n这么多位的s1,也就是用了need_n/len1这么多个s1,就拿到了now_num_s2 - memo[n][1]这么多个s2 // 还剩下max_n - now_n这么多个可以挥霍 int add_whole = (max_n - now_n) / (need_n / len1 * len1); now_num_s2 += add_whole * (now_num_s2 - memo[n].second + 1); now_n += add_whole * (need_n / len1 * len1); while (now_n < max_n) { temp = memo[now_n % len1].first; now_n = now_n / len1 * len1 + temp; if (now_n > max_n) { break; } now_num_s2 += 1; } return now_num_s2 / n2; } temp = checkWhere(n, s1, len1, s2, len2, memo); if (temp == -1) { return0; } now_n = now_n / len1 * len1 + temp; if (now_n > max_n) { break; } now_num_s2 += 1; memo[n] = pair<int, int>(temp, now_num_s2); } return now_num_s2 / n2; } };
classSolution { public: intfindMin(vector<int>& nums){ int len = nums.size(); int l = 0, r = len - 1; while (l <= r) { int mid = (l + r) / 2; if (nums[l] <= nums[r]) { return nums[l]; } if (nums[mid] <= nums[r]) { r = mid; // if mid == r, then l == r, so nums[l] == num[r] } else { l = mid + 1; // l won't be bigger than r } } return nums[r]; } };
classSolution { public: intfindMin(vector<int>& nums){ int len = nums.size(); int l = 0, r = len - 1; while (l <= r) { int mid = (l + r) / 2; if (nums[l] <= nums[r]) { return nums[l]; } if (nums[mid] > nums[mid + 1]) { // 在l和r不相等时,mid+1的下标是在范围内的 return nums[mid + 1]; } if (nums[mid] > nums[l]) { l = mid + 1; // l won't be bigger than r } else { r = mid; } } return nums[r]; } };