1
0

初めに

 今日から解いたLeetCodeの問題を解答含め解説していければと思います.
興味ある人はぜひご覧ください~~.と言っても,プログラミングの問題を解くのは殆ど初めてなので,「なんだこれ?」と思う人も多々いらっしゃると思います.なので,多めに見ていただきたいです~~

LeetCode (two sum )

問題はこちら

Given an array of integers nums and an integer target, return indices of the > two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may > > not use the same element twice.
You can return the answer in any order.

これは要約すると,「整数のリストとターゲットの値を上げるから,ターゲットの値を作る2つの数をリストから探してね」ってことですよね.多分.

ということでやってみましょう~~
早速解答はこちら.

def twoSum(self, nums: List[int], target: int) -> List[int]:
        indices =[]
        for i,outer in enumerate(nums):
            for j,inner in enumerate(nums):
                if outer + inner == target:
                    indices= [j,i]
                    break
        
        return indices

これは単純に外側のループで取得した要素と,内側のループの要素の合計がターゲットの値と一致する場合その時点での,iとjを格納する方法です.
ただ,このコードだと,同じ要素を二度使用することが許されていると,正確な条件の解を見つけることが出来ないですし,条件に合致する組み合わせが複数あると,最初に見つかった組み合わせしか返さないので正確性には欠けそうですね.

やっぱりまだまだですね~~
修業は続きそうです!

1
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
1
0