Skip to content

Commit 79c05eb

Browse files
committed
Added tasks 137-206
1 parent 3b89381 commit 79c05eb

File tree

13 files changed

+817
-68
lines changed

13 files changed

+817
-68
lines changed

README.md

+40-3
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang/fork)
3+
4+
## 137\. Single Number II
5+
6+
Medium
7+
8+
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
9+
10+
You must implement a solution with a linear runtime complexity and use only constant extra space.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [2,2,3,2]
15+
16+
**Output:** 3
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [0,1,0,1,0,1,99]
21+
22+
**Output:** 99
23+
24+
**Constraints:**
25+
26+
* <code>1 <= nums.length <= 3 * 10<sup>4</sup></code>
27+
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
28+
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
29+
30+
## Solution
31+
32+
```erlang
33+
-spec single_number(Nums :: [integer()]) -> integer().
34+
single_number(Nums) ->
35+
Frequencies = lists:foldl(fun count_frequency/2, #{}, Nums),
36+
{Key, _} = lists:keyfind(1, 2, maps:to_list(Frequencies)),
37+
Key.
38+
39+
-spec count_frequency(Num :: integer(), Map :: map()) -> map().
40+
count_frequency(Num, Map) ->
41+
maps:update_with(Num, fun(V) -> V + 1 end, 1, Map).
42+
```

src/main/erlang/g0101_0200/s0138_copy_list_with_random_pointer/readme.md

-65
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang/fork)
3+
4+
## 139\. Word Break
5+
6+
Medium
7+
8+
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
9+
10+
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "leetcode", wordDict = ["leet","code"]
15+
16+
**Output:** true
17+
18+
**Explanation:** Return true because "leetcode" can be segmented as "leet code".
19+
20+
**Example 2:**
21+
22+
**Input:** s = "applepenapple", wordDict = ["apple","pen"]
23+
24+
**Output:** true
25+
26+
**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple".
27+
28+
Note that you are allowed to reuse a dictionary word.
29+
30+
**Example 3:**
31+
32+
**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
33+
34+
**Output:** false
35+
36+
**Constraints:**
37+
38+
* `1 <= s.length <= 300`
39+
* `1 <= wordDict.length <= 1000`
40+
* `1 <= wordDict[i].length <= 20`
41+
* `s` and `wordDict[i]` consist of only lowercase English letters.
42+
* All the strings of `wordDict` are **unique**.
43+
44+
## Solution
45+
46+
```erlang
47+
-spec word_break(S :: unicode:unicode_binary(), WordDict :: [unicode:unicode_binary()]) -> boolean().
48+
word_break(S, WordDict) ->
49+
% Initialize ETS table for memoization
50+
ets:new(memo, [set, named_table]),
51+
% Process word dict to include sizes
52+
Words = [{Word, byte_size(Word)} || Word <- WordDict],
53+
% Get result
54+
Result = breakable(S, Words),
55+
% Clean up
56+
ets:delete(memo),
57+
Result.
58+
59+
-spec breakable(binary(), [{binary(), integer()}]) -> boolean().
60+
breakable(<<>>, _Words) ->
61+
true;
62+
breakable(S, Words) ->
63+
case ets:lookup(memo, S) of
64+
[{_, Result}] ->
65+
Result;
66+
[] ->
67+
Result = try_words(S, Words, Words),
68+
ets:insert(memo, {S, Result}),
69+
Result
70+
end.
71+
72+
try_words(_S, [], _AllWords) ->
73+
false;
74+
try_words(S, [{Word, Len} | Rest], AllWords) ->
75+
case S of
76+
<<Prefix:Len/binary, Remaining/binary>> when Prefix =:= Word ->
77+
case breakable(Remaining, AllWords) of
78+
true -> true;
79+
false -> try_words(S, Rest, AllWords)
80+
end;
81+
_ ->
82+
try_words(S, Rest, AllWords)
83+
end.
84+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang/fork)
3+
4+
## 146\. LRU Cache
5+
6+
Medium
7+
8+
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
9+
10+
Implement the `LRUCache` class:
11+
12+
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
13+
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
14+
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
15+
16+
The functions `get` and `put` must each run in `O(1)` average time complexity.
17+
18+
**Example 1:**
19+
20+
**Input** ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
21+
22+
**Output:** [null, null, null, 1, null, -1, null, -1, 3, 4]
23+
24+
**Explanation:**
25+
26+
LRUCache lRUCache = new LRUCache(2);
27+
28+
lRUCache.put(1, 1); // cache is {1=1}
29+
30+
lRUCache.put(2, 2); // cache is {1=1, 2=2}
31+
32+
lRUCache.get(1); // return 1
33+
34+
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
35+
36+
lRUCache.get(2); // returns -1 (not found)
37+
38+
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
39+
40+
lRUCache.get(1); // return -1 (not found)
41+
42+
lRUCache.get(3); // return 3
43+
44+
lRUCache.get(4); // return 4
45+
46+
**Constraints:**
47+
48+
* `1 <= capacity <= 3000`
49+
* <code>0 <= key <= 10<sup>4</sup></code>
50+
* <code>0 <= value <= 10<sup>5</sup></code>
51+
* At most <code>2 * 10<sup>5</sup></code> calls will be made to `get` and `put`.
52+
53+
## Solution
54+
55+
```erlang
56+
%% Persistent Term Keys
57+
-define(CAPACITY_KEY, {lru_cache, capacity}).
58+
-define(CACHE_TABLE, lru_cache_cache_table).
59+
-define(TTL_TABLE, lru_cache_ttl_table).
60+
61+
%% API Specifications
62+
-spec lru_cache_init_(Capacity :: integer()) -> ok.
63+
lru_cache_init_(Capacity) ->
64+
persistent_term:put(?CAPACITY_KEY, Capacity),
65+
case ets:info(?CACHE_TABLE) of
66+
undefined ->
67+
ets:new(?CACHE_TABLE, [set, public, named_table]),
68+
ets:new(?TTL_TABLE, [ordered_set, public, named_table]);
69+
_ ->
70+
ets:delete_all_objects(?CACHE_TABLE),
71+
ets:delete_all_objects(?TTL_TABLE)
72+
end,
73+
ok.
74+
75+
-spec lru_cache_get(Key :: integer()) -> integer().
76+
lru_cache_get(Key) ->
77+
case extract(Key) of
78+
{Key, Value} ->
79+
insert(Key, Value),
80+
Value;
81+
-1 ->
82+
-1
83+
end.
84+
85+
-spec lru_cache_put(Key :: integer(), Value :: integer()) -> ok.
86+
lru_cache_put(Key, Value) ->
87+
_ = extract(Key),
88+
insert(Key, Value),
89+
evict(),
90+
ok.
91+
92+
%% Internal Functions
93+
extract(Key) ->
94+
case ets:lookup(?CACHE_TABLE, Key) of
95+
[{Key, Uniq, Value}] ->
96+
ets:delete(?TTL_TABLE, Uniq),
97+
{Key, Value};
98+
[] ->
99+
-1
100+
end.
101+
102+
insert(Key, Value) ->
103+
Uniq = unique_integer(),
104+
ets:insert(?CACHE_TABLE, {Key, Uniq, Value}),
105+
ets:insert(?TTL_TABLE, {Uniq, Key}).
106+
107+
evict() ->
108+
Capacity = persistent_term:get(?CAPACITY_KEY),
109+
CurrentSize = ets:info(?CACHE_TABLE, size),
110+
if
111+
CurrentSize > Capacity ->
112+
Uniq = ets:first(?TTL_TABLE),
113+
[{_, Key}] = ets:lookup(?TTL_TABLE, Uniq),
114+
ets:delete(?TTL_TABLE, Uniq),
115+
ets:delete(?CACHE_TABLE, Key);
116+
true ->
117+
ok
118+
end.
119+
120+
unique_integer() ->
121+
erlang:unique_integer([monotonic]).
122+
123+
%% Your functions will be called as such:
124+
%% lru_cache_init_(Capacity),
125+
%% Param_1 = lru_cache_get(Key),
126+
%% lru_cache_put(Key, Value),
127+
128+
%% lru_cache_init_ will be called before every test case, in which you can do some necessary initializations.
129+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Erlang/LeetCode-in-Erlang?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Erlang/LeetCode-in-Erlang/fork)
3+
4+
## 148\. Sort List
5+
6+
Medium
7+
8+
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg)
13+
14+
**Input:** head = [4,2,1,3]
15+
16+
**Output:** [1,2,3,4]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg)
21+
22+
**Input:** head = [-1,5,3,4,0]
23+
24+
**Output:** [-1,0,3,4,5]
25+
26+
**Example 3:**
27+
28+
**Input:** head = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the list is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.
35+
* <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code>
36+
37+
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
38+
39+
## Solution
40+
41+
```erlang
42+
%% Definition for singly-linked list.
43+
%%
44+
%% -record(list_node, {val = 0 :: integer(),
45+
%% next = null :: 'null' | #list_node{}}).
46+
47+
%% @spec sort_list(Head :: #list_node{} | null) -> #list_node{} | null.
48+
-spec sort_list(Head :: #list_node{} | null) -> #list_node{} | null.
49+
sort_list(Head) ->
50+
List = node_to_list(Head, []),
51+
SortedList = lists:sort(fun(X, Y) -> X > Y end, List),
52+
list_to_node(SortedList, null).
53+
54+
%% Converts a linked list to an Erlang list.
55+
-spec node_to_list(Node :: #list_node{} | null, Acc :: [integer()]) -> [integer()].
56+
node_to_list(null, Acc) ->
57+
Acc;
58+
node_to_list(#list_node{val = Val, next = Next}, Acc) ->
59+
node_to_list(Next, [Val | Acc]).
60+
61+
%% Converts an Erlang list to a linked list.
62+
-spec list_to_node(List :: [integer()], Node :: #list_node{} | null) -> #list_node{} | null.
63+
list_to_node([], Node) ->
64+
Node;
65+
list_to_node([H | T], Node) ->
66+
list_to_node(T, #list_node{val = H, next = Node}).
67+
```

0 commit comments

Comments
 (0)