Skip to content

Conversation

@jiku0730
Copy link
Owner

software engineering協会で解いている人はいなかった。
LeetCodeの方で見てみる。

LeetCodeも見たけど、C言語でやってる人が少なすぎる😭

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++習得したほうが良いのかな。。。
Copy link

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]);
}
```
うーん。上手くいかなかった。
Copy link

@huyfififi huyfififi Jun 11, 2025

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)であまり差は現れなさそうですが。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants