Traverse each edge and count the out-degree of each point.
Time complexity: O(path.length * city[i].length), Space complexity: O(city.length * city[i].length).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: string destCity(vector<vector<string>>& paths){ unordered_map<string, int> outgoing; unordered_set<string> seen; for (constauto& v : paths) { ++outgoing[v[0]]; seen.insert(v[0]); seen.insert(v[1]); } for (constauto& s : seen) { if (outgoing[s] == 0) return s; } return""; } };
1437. Check If All 1’s Are at Least Length K Places Away
One pass. Record the position where the previous 1 appeared.
Time complexity: O(N), Space complexity: O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { constint INF = 0x3f3f3f3f; public: boolkLengthApart(vector<int>& nums, int k){ int last_one = -INF; for (int i = 0; i < nums.size(); ++i) { if (nums[i] == 1) { if (i - last_one - 1 >= k) { last_one = i; } else { returnfalse; } } } returntrue; } };
1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
Two pointers. Use a multiset to maintain the elements in the subarray. Because of the properties of TreeMap-like structures, we can quickly locate the maximum and minimum values in the subarray.
Time complexity: O(N log N), Space complexity: O(N).
classSolution { public: intlongestSubarray(vector<int>& nums, int limit){ multiset<int> subarray; size_t ans = 0; for (int r = 0, l = 0; r < nums.size(); ++r) { while (!subarray.empty() && nums[r] - *subarray.begin() > limit) { auto it = subarray.find(nums[l++]); subarray.erase(it); } while (!subarray.empty() && *subarray.rbegin() - nums[r] > limit) { auto it = subarray.find(nums[l++]); subarray.erase(it); } subarray.insert(nums[r]); ans = max(ans, subarray.size()); } return ans; } };
1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows
Use a priority queue to record all candidates. Select the combination with the smallest sum, and add the changed possible combinations into the priority queue.
One thing to note is that the same candidate may be generated from different states, such as 001, 010 -> 011. Here I used a set and string encoding to deduplicate.
Time complexity: O(k * m * m * log (nm)), Space complexity: O(n * m * m).