😇

leetcode Dart

2024/04/04に公開

問題を解いてみろ!

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.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

トピック 企業のヒント 整数の配列 nums と整数のターゲットを指定して、合計がターゲットになるような 2 つの数値のインデックスを返します。 各入力にはソリューションが 1 つだけ存在し、同じ要素を 2 回使用することはできないと想定できます。 回答は任意の順序で返すことができます。

何も分からん💦

どうするんだ....

  • ポイント
    ▫︎index[i]のことか?
    ▫︎配列???、DartならListか?
    ▫︎同じ要素を 2 回使用することはできないと想定できます。

解答code:

class Solution {
  List<int> twoSum(List<int> nums, int target) {
    var map = <int, int>{};
    for (var i = 0; i < nums.length; i++) {
      var complement = target - nums[i];
      if (map.containsKey(complement)) {
        return [map[complement]!, i];
      }
      map[nums[i]] = i;
    }
    throw Exception('No two sum solution');
  }
}

どうやら成功したようだ...
クラスはインスタンス化しなくもいいのか。Runボタンを押せば実行できる。


Listを作って、forでループして、containsKeyで指定したkeyがあればtrueを返さないといけないのか...
アルゴリズムを理解するの難しい💦
C++とかPythonより自分が得意な方の言語でアルゴリズムを勉強できそうなサービスを見つけました。

https://leetcode.com/

Discussion