-
Notifications
You must be signed in to change notification settings - Fork 0
1046. last stone weight #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| software engineering協会で解いている人はいなかった。 | ||
| LeetCodeの方で見てみる。 | ||
|
|
||
| LeetCodeも見たけど、C言語でやってる人が少なすぎる😭 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Max Heap や Priority Queue というデータ構造を使った解法があるので、それらを試してみるとよいと思います。
もしそれらのデータ構造に詳しくなければ、それら自体を実装してみることも勉強になると思います。
| LeetCodeの方で見てみる。 | ||
|
|
||
| LeetCodeも見たけど、C言語でやってる人が少なすぎる😭 | ||
| やっぱC++習得したほうが良いのかな。。。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
STL には出来合いのデータ構造が用意されています、C だとそこから作ることになるので、教育的にはいいんですが、ちょっと大変です。
| return (stones[0]); | ||
| } | ||
| ``` | ||
| うーん。上手くいかなかった。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
C言語に明るくないので読みづらいのは見逃して欲しいのですが、この方法だったら時間計算量 O(n^2)でいけますかね...?
int lastStoneWeight(int *stones, int stonesSize)
{
while (true) { // O(n) as one or two stones are processed for each loop
// get index of the heaviest stone and check num of stones, O(n)
int max_index = -1;
int max_weight = -1;
int num_stones = 0;
for (int i = 0; i < stonesSize; i++) {
if (stones[i] == 0) {
continue;
}
num_stones++;
if (stones[i] > max_weight) {
max_index = i;
max_weight = stones[i];
}
}
if (num_stones == 0) {
return 0;
} else if (num_stones == 1) {
return max_weight;
}
// get index of the second heaviest stone, O(n)
int second_max_index = -1;
int second_max_weight = -1;
for (int i = 0; i < stonesSize; i++) {
if (i == max_index) {
continue;
}
if (stones[i] > second_max_weight) {
second_max_index = i;
second_max_weight = stones[i];
}
}
stones[max_index] = stones[max_index] - stones[second_max_index];
stones[second_max_index] = 0;
}
}nがたかだか30くらいなので、heapを使う O(nlogn)、二重ループの O(n^2)、毎回ソートするO(n^2logn)であまり差は現れなさそうですが。
This problem
https://leetcode.com/problems/last-stone-weight/description/