|
| 1 | +#include <set> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public: |
| 6 | + /** |
| 7 | + * @brief LC: return min distance from start to destination [E] |
| 8 | + * there is only 2 ways to go from start to destination |
| 9 | + * Time: O(N), Space: O(1) |
| 10 | + * |
| 11 | + * @param distance |
| 12 | + * @param start |
| 13 | + * @param destination |
| 14 | + * @return int |
| 15 | + */ |
| 16 | + int distanceBetweenBusStop(vector<int>& distance, int start, |
| 17 | + int destination) { |
| 18 | + int sum = 0; |
| 19 | + for (int ele : distance) { |
| 20 | + sum += ele; |
| 21 | + } |
| 22 | + int ans = 0; |
| 23 | + if (start < destination) { |
| 24 | + for (int i = start; i < destination; i++) { |
| 25 | + ans += distance[i]; |
| 26 | + } |
| 27 | + } else if (start > destination) { |
| 28 | + for (int i = destination; i < start; i++) { |
| 29 | + ans += distance[i]; |
| 30 | + } |
| 31 | + } else { |
| 32 | + return 0; |
| 33 | + } |
| 34 | + return ans < (sum - ans) ? ans : (sum - ans); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @brief Sum swap [M] |
| 39 | + * Pure math, use hashset to store the temp arr |
| 40 | + * Time: O(N), Space: O(N), find for set is O(logN) |
| 41 | + * |
| 42 | + * @param array1 |
| 43 | + * @param array2 |
| 44 | + * @return vector<int> |
| 45 | + */ |
| 46 | + vector<int> findSwapValue(vector<int>& array1, vector<int>& array2) { |
| 47 | + int sum1 = 0, sum2 = 0; |
| 48 | + set<int> hashset; |
| 49 | + for (int arr : array1) { |
| 50 | + sum1 += arr; |
| 51 | + } |
| 52 | + for (int arr : array2) { |
| 53 | + sum2 += arr; |
| 54 | + hashset.insert(arr); |
| 55 | + } |
| 56 | + |
| 57 | + int diff = sum1 - sum2; |
| 58 | + if (diff % 2 != 0) { |
| 59 | + return {}; |
| 60 | + } |
| 61 | + diff /= 2; |
| 62 | + |
| 63 | + vector<int> ans(2, 0); |
| 64 | + for (int ele : array1) { |
| 65 | + if (hashset.find(ele - diff) != hashset.end()) { |
| 66 | + ans[0] = ele; |
| 67 | + ans[1] = ele - diff; |
| 68 | + return ans; |
| 69 | + } |
| 70 | + } |
| 71 | + return {}; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @brief LC1180: Sliding window [E] |
| 76 | + * Mind the edge of window, Time: O(N) Space: O(1) |
| 77 | + * |
| 78 | + * @param s |
| 79 | + * @return int |
| 80 | + */ |
| 81 | + int countLetters(string s) { |
| 82 | + int len = s.length(); |
| 83 | + int le = 0, ri = le; |
| 84 | + int ans = 0; |
| 85 | + |
| 86 | + while (le < len && le <= ri) { |
| 87 | + if (s[ri] == s[le]) { |
| 88 | + ans++; |
| 89 | + ri++; |
| 90 | + } else { |
| 91 | + le++; |
| 92 | + ri = le; |
| 93 | + } |
| 94 | + } |
| 95 | + return ans; |
| 96 | + } |
| 97 | +}; |
0 commit comments