From 57c84cc75c5c285d7e5e82fad65ac548b14ed200 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 9 May 2024 20:09:22 +0800 Subject: [PATCH 1/2] feat: add solutions to lc problem: No.2102 No.2102.Sequentially Ordinal Rank Tracker --- .../README.md | 183 ++++++++++++++++++ .../README_EN.md | 183 ++++++++++++++++++ .../Solution.cpp | 31 +++ .../Solution.py | 21 ++ .../Solution2.cpp | 30 +++ .../Solution2.java | 30 +++ .../Solution2.py | 28 +++ 7 files changed, 506 insertions(+) create mode 100644 solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.cpp create mode 100644 solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.py create mode 100644 solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.cpp create mode 100644 solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.java create mode 100644 solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md index 817b4657d7b4d..18521ba20bfa2 100644 --- a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md @@ -81,4 +81,187 @@ tracker.get(); // 从好到坏的景点为:branford, orlando, alp ## 解法 +### 方法一:有序集合 + +我们可以使用有序集合来存储景点,用一个变量 $i$ 来记录当前查询的次数,初始时 $i = -1$。 + +调用 `add` 方法时,我们将景点的评分取负数,这样就可以使用有序集合按照评分从大到小排序,如果评分相同,按照景点名字的字典序从小到大排序。 + +调用 `get` 方法时,我们将 $i$ 加一,然后返回有序集合中第 $i$ 个景点的名字。 + +每次操作的时间复杂度为 $O(\log n)$,其中 $n$ 为已添加的景点数。空间复杂度为 $O(n)$。 + + + +```python +from sortedcontainers import SortedList + + +class SORTracker: + + def __init__(self): + self.sl = SortedList() + self.i = -1 + + def add(self, name: str, score: int) -> None: + self.sl.add((-score, name)) + + def get(self) -> str: + self.i += 1 + return self.sl[self.i][1] + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() +``` + +```cpp +#include +#include +using namespace __gnu_pbds; + +template +using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + st.insert({-score, name}); + } + + string get() { + return st.find_by_order(++i)->second; + } + +private: + ordered_set> st; + int i = -1; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ +``` + + + +### 方法二:双优先队列(大小根堆) + +我们注意到,由于本题中的查询操作是按照严格递增的顺序进行的,因此我们可以使用类似于数据流中的中位数的方法,定义两个优先队列 `good` 和 `bad`,其中 `good` 是一个小根堆,存储当前最好的景点,`bad` 是一个大根堆,存储当前第 $i$ 好的景点。 + +每次调用 `add` 方法时,我们将景点的评分和名字加入 `good` 中,然后将 `good` 中的最差的景点加入 `bad` 中。 + +每次调用 `get` 方法时,我们将 `bad` 中的最好的景点加入 `good` 中,然后返回 `good` 中的最差的景点。 + +每次操作的时间复杂度为 $O(\log n)$,其中 $n$ 为已添加的景点数。空间复杂度为 $O(n)$。 + + + +```python +class Node: + def __init__(self, s: str): + self.s = s + + def __lt__(self, other): + return self.s > other.s + + +class SORTracker: + + def __init__(self): + self.good = [] + self.bad = [] + + def add(self, name: str, score: int) -> None: + score, node = heappushpop(self.good, (score, Node(name))) + heappush(self.bad, (-score, node.s)) + + def get(self) -> str: + score, name = heappop(self.bad) + heappush(self.good, (-score, Node(name))) + return self.good[0][1].s + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() +``` + +```java +class SORTracker { + private PriorityQueue> good = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? b.getValue().compareTo(a.getValue()) + : a.getKey() - b.getKey()); + private PriorityQueue> bad = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue()) + : b.getKey() - a.getKey()); + + public SORTracker() { + } + + public void add(String name, int score) { + good.offer(Map.entry(score, name)); + bad.offer(good.poll()); + } + + public String get() { + good.offer(bad.poll()); + return good.peek().getValue(); + } +} + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker obj = new SORTracker(); + * obj.add(name,score); + * String param_2 = obj.get(); + */ +``` + +```cpp +using pis = pair; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + good.push({-score, name}); + bad.push(good.top()); + good.pop(); + } + + string get() { + good.push(bad.top()); + bad.pop(); + return good.top().second; + } + +private: + priority_queue, less> good; + priority_queue, greater> bad; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ +``` + + + diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md index 98e72ca0695c9..f5c42b10b9f3c 100644 --- a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md @@ -77,4 +77,187 @@ tracker.get(); // Sorted locations: branford, orlando, alpine, alps ## Solutions +### Solution 1: Ordered Set + +We can use an ordered set to store the attractions, and a variable $i$ to record the current number of queries, initially $i = -1$. + +When calling the `add` method, we take the negative of the attraction's rating, so that we can use the ordered set to sort by rating in descending order. If the ratings are the same, sort by the dictionary order of the attraction names in ascending order. + +When calling the `get` method, we increment $i$ by one, and then return the name of the $i$-th attraction in the ordered set. + +The time complexity of each operation is $O(\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$. + + + +```python +from sortedcontainers import SortedList + + +class SORTracker: + + def __init__(self): + self.sl = SortedList() + self.i = -1 + + def add(self, name: str, score: int) -> None: + self.sl.add((-score, name)) + + def get(self) -> str: + self.i += 1 + return self.sl[self.i][1] + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() +``` + +```cpp +#include +#include +using namespace __gnu_pbds; + +template +using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + st.insert({-score, name}); + } + + string get() { + return st.find_by_order(++i)->second; + } + +private: + ordered_set> st; + int i = -1; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ +``` + + + +### Solution 2: Double Priority Queue (Min-Max Heap) + +We notice that the query operations in this problem are performed in strictly increasing order. Therefore, we can use a method similar to the median in the data stream. We define two priority queues `good` and `bad`. `good` is a min-heap, storing the current best attractions, and `bad` is a max-heap, storing the current $i$-th best attraction. + +Each time the `add` method is called, we add the attraction's rating and name to `good`, and then add the worst attraction in `good` to `bad`. + +Each time the `get` method is called, we add the best attraction in `bad` to `good`, and then return the worst attraction in `good`. + +The time complexity of each operation is $O(\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$. + + + +```python +class Node: + def __init__(self, s: str): + self.s = s + + def __lt__(self, other): + return self.s > other.s + + +class SORTracker: + + def __init__(self): + self.good = [] + self.bad = [] + + def add(self, name: str, score: int) -> None: + score, node = heappushpop(self.good, (score, Node(name))) + heappush(self.bad, (-score, node.s)) + + def get(self) -> str: + score, name = heappop(self.bad) + heappush(self.good, (-score, Node(name))) + return self.good[0][1].s + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() +``` + +```java +class SORTracker { + private PriorityQueue> good = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? b.getValue().compareTo(a.getValue()) + : a.getKey() - b.getKey()); + private PriorityQueue> bad = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue()) + : b.getKey() - a.getKey()); + + public SORTracker() { + } + + public void add(String name, int score) { + good.offer(Map.entry(score, name)); + bad.offer(good.poll()); + } + + public String get() { + good.offer(bad.poll()); + return good.peek().getValue(); + } +} + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker obj = new SORTracker(); + * obj.add(name,score); + * String param_2 = obj.get(); + */ +``` + +```cpp +using pis = pair; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + good.push({-score, name}); + bad.push(good.top()); + good.pop(); + } + + string get() { + good.push(bad.top()); + bad.pop(); + return good.top().second; + } + +private: + priority_queue, less> good; + priority_queue, greater> bad; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ +``` + + + diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.cpp b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.cpp new file mode 100644 index 0000000000000..169af995775ba --- /dev/null +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.cpp @@ -0,0 +1,31 @@ +#include +#include +using namespace __gnu_pbds; + +template +using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + st.insert({-score, name}); + } + + string get() { + return st.find_by_order(++i)->second; + } + +private: + ordered_set> st; + int i = -1; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ \ No newline at end of file diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.py b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.py new file mode 100644 index 0000000000000..120880a8304ce --- /dev/null +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedList + + +class SORTracker: + + def __init__(self): + self.sl = SortedList() + self.i = -1 + + def add(self, name: str, score: int) -> None: + self.sl.add((-score, name)) + + def get(self) -> str: + self.i += 1 + return self.sl[self.i][1] + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.cpp b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.cpp new file mode 100644 index 0000000000000..dc08195537ec7 --- /dev/null +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.cpp @@ -0,0 +1,30 @@ +using pis = pair; + +class SORTracker { +public: + SORTracker() { + } + + void add(string name, int score) { + good.push({-score, name}); + bad.push(good.top()); + good.pop(); + } + + string get() { + good.push(bad.top()); + bad.pop(); + return good.top().second; + } + +private: + priority_queue, less> good; + priority_queue, greater> bad; +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ \ No newline at end of file diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.java b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.java new file mode 100644 index 0000000000000..dc611afe0b5f7 --- /dev/null +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.java @@ -0,0 +1,30 @@ +class SORTracker { + private PriorityQueue> good = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? b.getValue().compareTo(a.getValue()) + : a.getKey() - b.getKey()); + private PriorityQueue> bad = new PriorityQueue<>( + (a, b) + -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue()) + : b.getKey() - a.getKey()); + + public SORTracker() { + } + + public void add(String name, int score) { + good.offer(Map.entry(score, name)); + bad.offer(good.poll()); + } + + public String get() { + good.offer(bad.poll()); + return good.peek().getValue(); + } +} + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker obj = new SORTracker(); + * obj.add(name,score); + * String param_2 = obj.get(); + */ \ No newline at end of file diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py new file mode 100644 index 0000000000000..34399cd696bfb --- /dev/null +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py @@ -0,0 +1,28 @@ +class Node: + def __init__(self, s: str): + self.s = s + + def __lt__(self, other): + return self.s > other.s + + +class SORTracker: + + def __init__(self): + self.good = [] + self.bad = [] + + def add(self, name: str, score: int) -> None: + score, node = heappushpop(self.good, (score, Node(name))) + heappush(self.bad, (-score, node.s)) + + def get(self) -> str: + score, name = heappop(self.bad) + heappush(self.good, (-score, Node(name))) + return self.good[0][1].s + + +# Your SORTracker object will be instantiated and called as such: +# obj = SORTracker() +# obj.add(name,score) +# param_2 = obj.get() From e3d9b948c7f3f6274144545c35387564a9e65b2a Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 9 May 2024 20:40:05 +0800 Subject: [PATCH 2/2] feat: update solutions to lc problem: No.2125 No.2125.Number of Laser Beams in a Bank --- .../README.md | 121 ++++++++---------- .../README_EN.md | 121 ++++++++---------- .../Solution.c | 17 ++- .../Solution.cpp | 16 +-- .../Solution.go | 15 +-- .../Solution.java | 19 ++- .../Solution.py | 10 +- .../Solution.rs | 20 ++- .../Solution.ts | 18 +-- 9 files changed, 157 insertions(+), 200 deletions(-) diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md index 41e17ae7e5793..7465a993efae5 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md @@ -66,36 +66,37 @@ ## 解法 -### 方法一 +### 方法一:逐行统计 + +我们可以逐行统计每行的安全设备数量,如果当前行没有安全设备,直接跳过,否则我们将当前行的安全设备数量乘以前一行的安全设备数量,累加到答案中。然后更新前一行的安全设备数量为当前行的安全设备数量。 + +时间复杂度 $O(m \times n)$,其中 $m$ 和 $n$ 分别为行数和列数。空间复杂度 $O(1)$。 ```python class Solution: def numberOfBeams(self, bank: List[str]) -> int: - last = ans = 0 - for b in bank: - if (t := b.count('1')) > 0: - ans += last * t - last = t + ans = pre = 0 + for row in bank: + if (cur := row.count("1")) > 0: + ans += pre * cur + pre = cur return ans ``` ```java class Solution { public int numberOfBeams(String[] bank) { - int last = 0; - int ans = 0; - for (String b : bank) { - int t = 0; - for (char c : b.toCharArray()) { - if (c == '1') { - ++t; - } + int ans = 0, pre = 0; + for (String row : bank) { + int cur = 0; + for (int i = 0; i < row.length(); ++i) { + cur += row.charAt(i) - '0'; } - if (t > 0) { - ans += last * t; - last = t; + if (cur > 0) { + ans += pre * cur; + pre = cur; } } return ans; @@ -107,16 +108,12 @@ class Solution { class Solution { public: int numberOfBeams(vector& bank) { - int ans = 0; - int last = 0; - for (auto& b : bank) { - int t = 0; - for (char& c : b) - if (c == '1') - ++t; - if (t) { - ans += last * t; - last = t; + int ans = 0, pre = 0; + for (auto& row : bank) { + int cur = count(row.begin(), row.end(), '1'); + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; @@ -125,33 +122,26 @@ public: ``` ```go -func numberOfBeams(bank []string) int { - ans, last := 0, 0 - for _, b := range bank { - t := strings.Count(b, "1") - if t > 0 { - ans += t * last - last = t +func numberOfBeams(bank []string) (ans int) { + pre := 0 + for _, row := range bank { + if cur := strings.Count(row, "1"); cur > 0 { + ans += pre * cur + pre = cur } } - return ans + return } ``` ```ts function numberOfBeams(bank: string[]): number { - let last = 0; - let ans = 0; - for (const r of bank) { - let t = 0; - for (const v of r) { - if (v === '1') { - t++; - } - } - if (t !== 0) { - ans += last * t; - last = t; + let [ans, pre] = [0, 0]; + for (const row of bank) { + const cur = row.split('1').length - 1; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; @@ -161,18 +151,16 @@ function numberOfBeams(bank: string[]): number { ```rust impl Solution { pub fn number_of_beams(bank: Vec) -> i32 { - let mut last = 0; let mut ans = 0; - for r in bank.iter() { - let mut t = 0; - for &v in r.as_bytes() { - if v == b'1' { - t += 1; - } - } - if t != 0 { - ans += last * t; - last = t; + let mut pre = 0; + for row in bank { + let cur = row + .chars() + .filter(|&c| c == '1') + .count() as i32; + if cur > 0 { + ans += pre * cur; + pre = cur; } } ans @@ -182,18 +170,17 @@ impl Solution { ```c int numberOfBeams(char** bank, int bankSize) { - int last = 0; - int ans = 0; - for (int i = 0; i < bankSize; i++) { - int t = 0; - for (int j = 0; bank[i][j]; j++) { + int ans = 0, pre = 0; + for (int i = 0; i < bankSize; ++i) { + int cur = 0; + for (int j = 0; bank[i][j] != '\0'; ++j) { if (bank[i][j] == '1') { - t++; + cur++; } } - if (t != 0) { - ans += last * t; - last = t; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md index ab5e625fd1025..1e136f55ae3e1 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md @@ -58,36 +58,37 @@ This is because the 2nd row contains security devices, which breaks t ## Solutions -### Solution 1 +### Solution 1: Row by Row Counting + +We can count the number of safety devices row by row. If the current row does not have any safety devices, we skip it. Otherwise, we multiply the number of safety devices in the current row by the number of safety devices in the previous row, and add it to the answer. Then we update the number of safety devices in the previous row to be the number of safety devices in the current row. + +The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns, respectively. The space complexity is $O(1)$. ```python class Solution: def numberOfBeams(self, bank: List[str]) -> int: - last = ans = 0 - for b in bank: - if (t := b.count('1')) > 0: - ans += last * t - last = t + ans = pre = 0 + for row in bank: + if (cur := row.count("1")) > 0: + ans += pre * cur + pre = cur return ans ``` ```java class Solution { public int numberOfBeams(String[] bank) { - int last = 0; - int ans = 0; - for (String b : bank) { - int t = 0; - for (char c : b.toCharArray()) { - if (c == '1') { - ++t; - } + int ans = 0, pre = 0; + for (String row : bank) { + int cur = 0; + for (int i = 0; i < row.length(); ++i) { + cur += row.charAt(i) - '0'; } - if (t > 0) { - ans += last * t; - last = t; + if (cur > 0) { + ans += pre * cur; + pre = cur; } } return ans; @@ -99,16 +100,12 @@ class Solution { class Solution { public: int numberOfBeams(vector& bank) { - int ans = 0; - int last = 0; - for (auto& b : bank) { - int t = 0; - for (char& c : b) - if (c == '1') - ++t; - if (t) { - ans += last * t; - last = t; + int ans = 0, pre = 0; + for (auto& row : bank) { + int cur = count(row.begin(), row.end(), '1'); + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; @@ -117,33 +114,26 @@ public: ``` ```go -func numberOfBeams(bank []string) int { - ans, last := 0, 0 - for _, b := range bank { - t := strings.Count(b, "1") - if t > 0 { - ans += t * last - last = t +func numberOfBeams(bank []string) (ans int) { + pre := 0 + for _, row := range bank { + if cur := strings.Count(row, "1"); cur > 0 { + ans += pre * cur + pre = cur } } - return ans + return } ``` ```ts function numberOfBeams(bank: string[]): number { - let last = 0; - let ans = 0; - for (const r of bank) { - let t = 0; - for (const v of r) { - if (v === '1') { - t++; - } - } - if (t !== 0) { - ans += last * t; - last = t; + let [ans, pre] = [0, 0]; + for (const row of bank) { + const cur = row.split('1').length - 1; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; @@ -153,18 +143,16 @@ function numberOfBeams(bank: string[]): number { ```rust impl Solution { pub fn number_of_beams(bank: Vec) -> i32 { - let mut last = 0; let mut ans = 0; - for r in bank.iter() { - let mut t = 0; - for &v in r.as_bytes() { - if v == b'1' { - t += 1; - } - } - if t != 0 { - ans += last * t; - last = t; + let mut pre = 0; + for row in bank { + let cur = row + .chars() + .filter(|&c| c == '1') + .count() as i32; + if cur > 0 { + ans += pre * cur; + pre = cur; } } ans @@ -174,18 +162,17 @@ impl Solution { ```c int numberOfBeams(char** bank, int bankSize) { - int last = 0; - int ans = 0; - for (int i = 0; i < bankSize; i++) { - int t = 0; - for (int j = 0; bank[i][j]; j++) { + int ans = 0, pre = 0; + for (int i = 0; i < bankSize; ++i) { + int cur = 0; + for (int j = 0; bank[i][j] != '\0'; ++j) { if (bank[i][j] == '1') { - t++; + cur++; } } - if (t != 0) { - ans += last * t; - last = t; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c index 43f6fa52c7b65..893391d1cf934 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.c @@ -1,16 +1,15 @@ int numberOfBeams(char** bank, int bankSize) { - int last = 0; - int ans = 0; - for (int i = 0; i < bankSize; i++) { - int t = 0; - for (int j = 0; bank[i][j]; j++) { + int ans = 0, pre = 0; + for (int i = 0; i < bankSize; ++i) { + int cur = 0; + for (int j = 0; bank[i][j] != '\0'; ++j) { if (bank[i][j] == '1') { - t++; + cur++; } } - if (t != 0) { - ans += last * t; - last = t; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.cpp b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.cpp index 82ab4c5c5d54a..24b6ba29f07b1 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.cpp +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.cpp @@ -1,16 +1,12 @@ class Solution { public: int numberOfBeams(vector& bank) { - int ans = 0; - int last = 0; - for (auto& b : bank) { - int t = 0; - for (char& c : b) - if (c == '1') - ++t; - if (t) { - ans += last * t; - last = t; + int ans = 0, pre = 0; + for (auto& row : bank) { + int cur = count(row.begin(), row.end(), '1'); + if (cur) { + ans += pre * cur; + pre = cur; } } return ans; diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.go b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.go index 4ad18b69d9706..e93faef90864f 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.go +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.go @@ -1,11 +1,10 @@ -func numberOfBeams(bank []string) int { - ans, last := 0, 0 - for _, b := range bank { - t := strings.Count(b, "1") - if t > 0 { - ans += t * last - last = t +func numberOfBeams(bank []string) (ans int) { + pre := 0 + for _, row := range bank { + if cur := strings.Count(row, "1"); cur > 0 { + ans += pre * cur + pre = cur } } - return ans + return } \ No newline at end of file diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.java b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.java index d928f3393c3eb..2330f6829c2b1 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.java +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.java @@ -1,17 +1,14 @@ class Solution { public int numberOfBeams(String[] bank) { - int last = 0; - int ans = 0; - for (String b : bank) { - int t = 0; - for (char c : b.toCharArray()) { - if (c == '1') { - ++t; - } + int ans = 0, pre = 0; + for (String row : bank) { + int cur = 0; + for (int i = 0; i < row.length(); ++i) { + cur += row.charAt(i) - '0'; } - if (t > 0) { - ans += last * t; - last = t; + if (cur > 0) { + ans += pre * cur; + pre = cur; } } return ans; diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py index 45d0e10ca91cb..f665ea2a0598a 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py @@ -1,8 +1,8 @@ class Solution: def numberOfBeams(self, bank: List[str]) -> int: - last = ans = 0 - for b in bank: - if (t := b.count('1')) > 0: - ans += last * t - last = t + ans = pre = 0 + for row in bank: + if (cur := row.count("1")) > 0: + ans += pre * cur + pre = cur return ans diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.rs b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.rs index f9e8b154d6b01..834ef62c07513 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.rs +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.rs @@ -1,17 +1,15 @@ impl Solution { pub fn number_of_beams(bank: Vec) -> i32 { - let mut last = 0; let mut ans = 0; - for r in bank.iter() { - let mut t = 0; - for &v in r.as_bytes() { - if v == b'1' { - t += 1; - } - } - if t != 0 { - ans += last * t; - last = t; + let mut pre = 0; + for row in bank { + let cur = row + .chars() + .filter(|&c| c == '1') + .count() as i32; + if cur > 0 { + ans += pre * cur; + pre = cur; } } ans diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.ts b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.ts index be0d831b24317..c8e05d21bd82d 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.ts +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.ts @@ -1,16 +1,10 @@ function numberOfBeams(bank: string[]): number { - let last = 0; - let ans = 0; - for (const r of bank) { - let t = 0; - for (const v of r) { - if (v === '1') { - t++; - } - } - if (t !== 0) { - ans += last * t; - last = t; + let [ans, pre] = [0, 0]; + for (const row of bank) { + const cur = row.split('1').length - 1; + if (cur) { + ans += pre * cur; + pre = cur; } } return ans;