LoginSignup
0
0

LeetCodeでひっかかったあれこれ

Last updated at Posted at 2023-09-05

筆者がleetcodeで止まったことのあれこれを書いてます!

range

for i in range(len(nums)-2, 0, -1): 
  # nums = [1,1,1,2,2,3]の場合
  # i : 4(第1引数は含む) -> 1(第2引数は手前まで)



pop

nums.pop(i+1)
  # pop(index)で、そのindexをリストから削除できる

popは、pop()で末尾を取り除くだけではなかったんですね!



vscodeでのデバッグ

をクリックすると、関数内に入っての実行ができる。



型ヒント

from typing import List

型ヒントでエラーが出たらこれです!



vscodeでの実行

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    # ↓↓↓実行↓↓↓
    print(Solution().removeDuplicates(nums))



sortとsorted

# sort  : 破壊的
l = [9, 5, 3, 1, 7]
l.sort()
print(l)         # [1, 3, 5, 7, 9]

# sorted: 非破壊的
l = [9, 5, 3, 1, 7]
l_sorted = sorted(l)  # lの位置も違います! 
print(l_sorted)  # [1, 3, 5, 7, 9]
print(l)         # [9, 5, 3, 1, 7]



リストの中身を順々に使っていく

list = [5, 7, 1]

for list_element in list:
    print(list_element)
# 5
# 7
# 1



文字列はリストに変換なくても、forでそのまま使えます!

for symbol in "MCXV":
    print(symbol)
# M
# C
# X
# V



辞書型の超基本(なかなか使わないので、忘れてました)

dict={ "a":"apple" , "b":"banana" , "c":"choco" }
print(dict["a"]) # 引数はキーです
# apple

# 値の追加
dict1["d"]="dessert"
print(dict1)
# {'a': 'apple', 'b': 'banana', 'c': 'choco' , 'd': 'dessert'}



replaceに再帰性はない

str = "aaabb"
str = str.replace("ab", "bb")
print("replace x 1回:",str)

str = str.replace("ab", "bb")
print("replace x 2回:",str)

# replace x 1回: aabbb
# replace x 2回: abbbb

まあ、普通は再帰的に実行されるとは思いませんが、leetcodeをしている時にふと不安になったので。



replaceは再代入が必要

str = "fix me"
str_fixed = str.replace("fix", "fixed")
print(str)
# fix me

print(str_fixed)
# fixed me

strreplaceが反映されていないことがポイントです!



文字列でも~[i]が使える!

string = "STR"
print(string[1])
# T



文字列の連結は+でOK

string = "STR"
integer = "int"
print(string + integer)
# STRint



リスト要素をforで取り出す時、range(len(list))は不要

words = ["flower","flow","flight"]
for word in words:
    print(word)
# flower
# flow
# flight



stripは前後の指定文字を消す

space_words_space = "  some  spaces  "
print("->"+space_words_space+";")
# ->  some  spaces  ;

only_words = space_words_space.strip()
print("->"+only_words+";")
# ->some  spaces;



リストの逆順は、reverse()もしくは~[::-1]

normal_list = [1, 2, 3, 4, 5]
normal_list.reverse()
print(normal_list)
# [5, 4, 3, 2, 1]

normal = [1, 2, 3, 4, 5]
reverse = normal[::-1]
print(reverse)
# [5, 4, 3, 2, 1]



split(引数なし)は、スペースが複数挟まってても全部削除してくれる!

s = "a good   example"
s = s.split()
print(s)
# ['a', 'good', 'example']



set型にすると重複がなくなる

pattern = "abba"
set_pattern = set(pattern)
print(set_pattern)
# {'b', 'a'}



長い方に合わせるzipzip_longest

str_num = ['one', 'two', 'three']
int_num = [1, 2]
for str_int in zip(str_num, int_num):
    print(str_int)
# ('one', 1)
# ('two', 2)
    
from itertools import zip_longest
for str_int in zip_longest(str_num, int_num):
    print(str_int)
# ('one', 1)
# ('two', 2)
# ('three', None)

zipは、最も短いものに合わせます。



A == B == Cは可能!

test1, test2, test3 = "test", "test", "test"
print(test1 == test2 == test3)
# True



要素 -> インデックス は、index

nums = [30, 50, 10, 40, 20]
print(nums.index(20))
# 4



window問題は、for&forではなく、for&while

# nums = [2,3,1,2,4,3]
# target = 7
for i in range(len(nums)):
    total += nums[i]
    while total >= target:
        element_counter = min(element_counter, i-left_index+1)
        total -= nums[left_index]
        left_index += 1

for&forだと、左indexを増やせません。
該当問題:209. Minimum Size Subarray Sum



rangeの第一引数で、forの最初のインデックスを指定できる

nums = [0, 1, 2, 3]
for i in range(2, len(nums)):
    print(i)
# 2
# 3

# 普段のrange
for i in range(0, len(nums)):
    print(i)
# 0
# 1
# 2
# 3



文字列でもlen()可能

test_string = "test"
print(len(test_string))
# 4



集合

初期化=>set()もしくは{ 要素 }

empty_set = set()
print(type(empty_set))
# <class 'set'>

even_nums = {0, 2, 4, 6}
print(type(even_nums))
# <class 'set'>

集合(set型)には要素順序なし。


要素追加=>add

nums = set((1, 2, 3))  # タプルから集合を生成
print(nums)
# {1, 2, 3}

nums.add(4)
print(nums)
# {1, 2, 3, 4}



リストの一番最後:~[-1]








メモリパフォーマンス向上





番外編

zip

二つのリストを対応させながら処理したい時に有効です!

names  = ['momo', 'urashima', 'kaguya']
ages   = [16, 20, 18]
zipped = zip(names, ages)
for name, age in zipped:
   print( 'name:' + name + '  age:' + str(age) )
# name:momo  age:16
# name:urashima  age:20
# name:kaguya  age:18

# castとすると型変更できます
dictionary = dict(zipped)

参考URL



in listは死ぬほど遅い、in setを使うべき!

参考Qiita



tuplesetは別物

example_set = set()
print(type(example_set))
# <class 'set'>

# tupleは要素変更できないlist
example_tuple = ('test',)
print(type(example_tuple))
# <class 'tuple'>




良さげな変数名

一時保存の合計値

# sumは、sum関数と被る
total
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0