I’m learning Elixir with Leetcode.
The Leetcode problem is Valid Triangle Number.
My Rust solution uses two pointers with array
impl Solution {
pub fn triangle_number(mut nums: Vec<i32>) -> i32 {
nums.sort();
let mut ans = 0;
for i in 2..nums.len() {
let mut left = 0;
let mut right = i - 1;
while left < right {
if nums[left] + nums[right] > nums[i] {
ans += right - left;
right -= 1;
} else {
left += 1;
}
}
}
ans as i32
}
}
I got Timeout when I trying to convert this code to Elixir.
defmodule Solution do
@spec triangle_number(nums :: [integer]) :: integer
def triangle_number(nums) do
len = Enum.count(nums)
if len < 3 do
0
else
nums |> Enum.sort |> loop_nums(2, len)
end
end
def loop_nums(nums, i, len) do
if i == len do
0
else
check_intervals(nums, 0, i - 1, i) + loop_nums(nums, i + 1, len)
end
end
def check_intervals(nums, a, b, c) do
cond do
a >= b -> 0
Enum.at(nums, a) + Enum.at(nums, b) > Enum.at(nums, c) -> b - a + check_intervals(nums, a, b - 1, c)
true -> check_intervals(nums, a + 1, b, c)
end
end
end
How to improve the performance?
Thank you.






















