2221. Find Triangular Sum of an Array
T:O(n^2)
S:O(n^2)
class Solution {
public int triangularSum(int[] nums) {
List<Integer> list = new ArrayList<>();
for (int num : nums) {
list.add(num);
}
List<Integer> temp = new ArrayList<>();
while (list.size() != 1) {
for (int i = 0; i < list.size()-1; i++) {
temp.add((list.get(i) + list.get(i+1))%10);
}
list = temp;
temp = new ArrayList<>();
}
return list.get(0);
}
}
T:O(n^2)
S:O(1)
```java
class Solution {
public int triangularSum(int[] nums) {
int n = nums.length;
while (n > 1) {
for (int i = 0; i < n-1; i++) {
nums[i] = (nums[i] + nums[i+1])%10;
}
n--;
}
return nums[0];
}
}
// still T: O(n^2) but space: O(1) in place
```
Last updated