跳至主要内容

268 篇文章 含有標籤「leetcode」

檢視所有標籤

274. H-Index

· 閱讀時間約 2 分鐘

Hint - Sort

class Solution {
public:
int hIndex(vector<int>& citations)
{
// Sort the citations in descending order

// Initialize the index variable

// Loop through the sorted citations array
// Check if the citation count is greater than the current index
// Increment the index
// Return the H-Index
}
};
  • Sort
class Solution {
public:
int hIndex(vector<int>& citations)
{
sort(citations.rbegin(), citations.rend());
int i = 0;
while (i < citations.size() && citations[i] > i) ++i;
return i;
}
};
  • T: $O(N \log N)$
  • S: $O(1)$

Hint - HashMap

class Solution {
public:
// Function to calculate the H-Index given a list of citation counts
int hIndex(vector<int>& citations)
{
// Map to store the frequency of each citation count

// Populate the map with citation counts and their frequencies

// Convert the map to a vector of pairs and sort it in descending order of citation counts
// m.rbegin() and m.rend() reverse the order of the map

// Initialize the count of papers that have at least 'cnt' citations

// Iterate through the sorted list of citation counts and their frequencies
for ()
{
// If the current citation count is greater than the current count plus the number of papers with this citation count
if ()
{
// Increase the count by the number of papers with this citation count
}
// If the current citation count is equal to the current count plus the number of papers with this citation count
else if ()
{
// Return the current citation count as the H-Index
}
// If the current citation count is less than the current count plus the number of papers with this citation count
else
{
// Return the maximum of the current citation count and the current count as the H-Index
}
}
// If we have iterated through all the citation counts and not returned, return the count as the H-Index
}
};
  • HashMap
class Solution {
public:
int hIndex(vector<int>& citations)
{
map<int, int> m;
for (int i = 0; i < citations.size(); ++i) ++m[citations[i]];

vector<pair<int, int>> q(m.rbegin(), m.rend());

int cnt = 0;
for (int i = 0; i < q.size(); ++i)
{
if (q[i].first > cnt + q[i].second)
{
cnt += q[i].second;
}
else if (q[i].first == cnt + q[i].second)
{
return q[i].first;
}
else
{
return max(q[i].first, cnt);
}
}
return cnt;
}
};
  • T: $O(n)$
  • S: $O(n)$

273. Integer to English Words

· 閱讀時間約 2 分鐘
/*
* @lc app=leetcode id=273 lang=cpp
*
* [273] Integer to English Words
*
* https://leetcode.com/problems/integer-to-english-words/description/
*
* algorithms
* Hard (34.09%)
* Likes: 3738
* Dislikes: 6794
* Total Accepted: 544.8K
* Total Submissions: 1.6M
* Testcase Example: '123'
*
* Convert a non-negative integer num to its English words representation.
*
*
* Example 1:
*
*
* Input: num = 123
* Output: "One Hundred Twenty Three"
*
*
* Example 2:
*
*
* Input: num = 12345
* Output: "Twelve Thousand Three Hundred Forty Five"
*
*
* Example 3:
*
*
* Input: num = 1234567
* Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
* Seven"
*
*
*
* Constraints:
*
*
* 0 <= num <= 2^31 - 1
*
*
*/

// @lc code=start
class Solution {
public:
string numberToWords(int num) {
if (num == 0) return "Zero";

vector<pair<int, string>> units = {
{1000000000, "Billion"},
{1000000, "Million"},
{1000, "Thousand"},
{1, ""}
};

string res;
for (auto& [val, name] : units) {
if (num >= val) {
string segment = helper(num / val);
res += segment + (name.empty() ? "" : " " + name) + " ";
num %= val;
}
}
while (!res.empty() && res.back() == ' ') res.pop_back();
return res;
}
string helper(int num) {
vector<string> below_20 = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
vector<string> tens = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
string res;
if (num < 20) {
res = below_20[num];
} else if (num < 100) {
res = tens[num / 10];
if (num % 10 != 0) {
res += " " + helper(num % 10);
}
return res;
} else {
res = below_20[num / 100] + " Hundred";
if (num % 100 != 0) {
res += " " + helper(num % 100);
}
}
return res;
}
};
// @lc code=end

271. Encode and Decode Strings

· 閱讀時間約 1 分鐘
class Codec {
public:

// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for (auto& a : strs) {
// 轉成size/字串size/字串size/字串
// ["Hello","World"] -> 5/Hello5/World
res.append(to_string(a.size())).append("/").append(a);
}
return res;
}

// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
int i = 0;
while (i < s.size()) {
// 找到分隔號的位置
auto found = s.find("/", i);

// 得到字串長度
int len = stoi(s.substr(i, found - i));

// 將字串推到 array
res.push_back(s.substr(found + 1, len));

// 下一根指針
i = found + len + 1;
}
return res;
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));
  • T: $O(N)$
  • S: $O(N)$

268. Missing Number

· 閱讀時間約 1 分鐘

Sort

class Solution {
public:
int missingNumber(vector<int>& nums)
{
int n = nums.size();
for(int i = 0; i < nums.size(); i++)
{
n += i - nums[i];
}
return n;
}
};
  • T: $O(n)$
  • S: $O(1)$

261. Graph Valid Tree

· 閱讀時間約 1 分鐘
class Solution {
public:
bool validTree(int n, vector<vector<int>>& edges)
{
vector<vector<int>> graph(n, vector<int>());
for (auto& edge : edges)
{
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}

unordered_set<int> seen;
return dfs(graph, seen, 0, -1) && seen.size() == n;
}

bool dfs(vector<vector<int>>& graph, unordered_set<int>& seen, int node, int parent)
{
if (seen.count(node)) return false;

seen.insert(node);

for(int nei : graph[node])
{
if (parent != nei)
{
if (!dfs(graph, seen, nei, node))
return false;
}
}
return true;
}
};
  • T: $O(V + E)$
  • S: $O(V + E)$

257. Binary Tree Paths

· 閱讀時間約 2 分鐘

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Example 1:

image

Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1] Output: ["1"]

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100

recursion

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
dfs(root, "", res);
return res;
}

void dfs(TreeNode* root, string out, vector<string>& res) {
if(!root->left && !root->right) {
res.push_back(out + to_string(root->val));
}
if(root->left) {
dfs(root->left, out + to_string(root->val) + "->", res);
}
if(root->right) {
dfs(root->right, out + to_string(root->val) + "->", res);
}
}
};
  • T: $O(N)$
  • S: $O(N)$

iteration

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
// base case
if(!root) return res;

// 如果沒有左右子節點,則返回 root
if(!root->left && !root->right) {
return {to_string(root->val)};
}

// 找左側
for(auto s : binaryTreePaths(root->left)) {
res.push_back(to_string(root->val) + "->" + s);
}

// 找右側
for(auto s : binaryTreePaths(root->right)) {
res.push_back(to_string(root->val) + "->" + s);
}

return res;
}
};
  • T: $O(N)$
  • S: $O(N)$

253. Meeting Rooms II

· 閱讀時間約 1 分鐘

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]] Output: 2

Example 2:

Input: intervals = [[7,10],[2,4]] Output: 1

Constraints:

  • 1 <= intervals.length <= 104
  • 0 <= starti < endi <= 106
class Solution {
public:
int minMeetingRooms(vector<vector<int>>& intervals) {
int n = intervals.size();

sort(intervals.begin(), intervals.end());
priority_queue<int, vector<int>, greater<int>> minHeap;

// #0: minHeap = [30];
// #1: minHeap = [10, 30];
// #2: minHeap = [10, 20];
for (auto& interval : intervals) {
if (!minHeap.empty() && interval[0] >= minHeap.top()) {
minHeap.pop();
}
minHeap.push(interval[1]);
}
return minHeap.size();
}
};
  • T: $O(N \log N)$
  • S: $O(N)$

252. Meeting Rooms

· 閱讀時間約 1 分鐘

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]] Output: false

Example 2:

Input: intervals = [[7,10],[2,4]] Output: true

Constraints:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti < endi <= 106

算區間是否重疊,如果重疊 return false

class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
int n = intervals.size();
if (n == 0) return true;
sort(intervals.begin(), intervals.end());
for(int i = 0; i < n - 1; i++) {
// 如果目前區間的 endtime 比下一個區間的 start time 大的話
// 代表有 overlap
if (intervals[i].back() > intervals[i + 1].front())
return false;
}
return true;
}
};
  • T: $O(N \cdot \log N)$,取決於排序演算法
  • S: $O(1)$

242. Valid Anagram

· 閱讀時間約 1 分鐘
class Solution {
public:
bool isAnagram(string s, string t)
{
if (s.size() != t.size()) return false;

unordered_map<char, int> m;

for(auto& c : s) ++m[c];

for (auto& c : t)
{
if (m.count(c))
{
--m[c];
if (!m[c]) m.erase(c);
}
}
return !m.size();
}
};
  • T: $O(N)$
  • S: $O(1)$