challenge 重複する要素を取り除く

与えられたリストxsの中から、 2回以上出現するものを全部取り除いてください。

サンプル入力
[3, 1, 4, 1, 5, 9, 2, 6, 5]
サンプル出力
[3, 4, 9, 2, 6]

これはアレイのuniqの派生問題です。 リストとかアレイという言葉は言語によってまちまちの意味で使われているので、 「配列のようなもの」という漠然とした意味にとって構いません。

Posted feedbacks - SQL

SQLで「配列のようなもの」をどう考えるかで悩んだ時間の方が長かったです。
テーブルを使うのは都合良すぎで、お題から外れるような気がするのですが。
1
2
3
4
5
6
7
8
9
drop table if exists xs;
create table xs(id int not null auto_increment primary key, x int not null);
insert into xs(x) values (3), (1), (4), (1), (5), (9), (2), (6), (5);

select
  x
from xs
group by x having count(x) < 2
order by min(id);

'3, 1, 4, 1, 5, 9, 2, 6, 5'という「配列のような文字列」をカンマで区切って重複を調べます。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
set @xs = '3, 1, 4, 1, 5, 9, 2, 6, 5';

drop table if exists num_chars;
create table num_chars(id int not null);
insert into num_chars values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

drop table if exists nums;
create table nums as (
  select n1.id + (n2.id * 10) + (n3.id * 100) as id
  from num_chars n1, num_chars n2, num_chars n3);

select
  x
from (
  select
    num
  , trim(substring_index(substring_index(@xs, ',', num), ',', -1)) as x
  from (
    select id as num from nums
    where id >= 1
      and id <= (length(@xs) - length(replace(@xs, ',', '')) + 1)
    ) as nums
  ) as xs
group by x having count(x) < 2
order by min(num);

Index

Feed

Other

Link

Pathtraq

loading...