Dart의 두 합계 솔루션 - LeetCode

Dart의 TwoSum 솔루션



LeetCode

첫 번째 솔루션




class Solution {
  // BRUTE FORCE SOLUTION - SIMPLE
  // Runtime of this solution is 362ms
  List<int> twoSum(List<int> numbers, int target) {
    // it indicates the whole length of the list
    int n = numbers.length;

// for loop for tracking the first value
    for (var i = 0; i < n - 1; i++) {
      // for loop for keep tracking the second value inside the list
      for (var j = i + 1; j < n; j++) {
        // condition that dictates the first of any value inside the list and second inside the
        // list should be equal to target
        if (numbers[i] + numbers[j] == target) {
          // then we return the list of first value and second
          return [i, j];
        }
      }
    }

    return [];
  }
}


두 번째 솔루션



지도를 사용하여 목록의 값을 주시하십시오.
슬프게도 LeetCode에서 HashMap은 작동하지 않지만 leetcode 외부에서는 완벽하게 작동합니다.
그래서 Hash Map 대신 Map을 사용합니다.


class Solution {
  // In LeetCode the HashMap is not fully implemented
  // Runtime 503
  List<int> twoSum(List<int> nums, int target) {


// Map to keep an eye on the close range, simply correlation
    final Map<int, int> correspondence = Map<int, int>();

    // loop through the entire list values
    for (var i = 0; i < nums.length; i++) {
      // saving value inside a variable
      final int value = nums[i];

      // we are getting key in a very tricky way like target value which
      // we will enter and than we will subtract the single value
      //that we got from looping from the list.
      //
      final int key = target - value;
      if (correspondence.containsKey(key)) {
        // than we will return if int of the map and the second int
        // which shows the position in a list which two value will result the target value
        return [correspondence[key]!, i];
      }
      // here we defining that our key will i the digit inside of our list
      // if we don't do  this than it will return the value of the list which is inside the list
      correspondence[value] = i;

      // Remember = correspondence[key] is Our key , correspondence[value] is Our Value

    }
    return [];
  }
}



세 번째 솔루션



dart는 목록의 인덱스 번호를 추적하지 않기 때문에 이것은 터미널의 매력처럼 작동합니다. 목록으로 작업할 확장을 만들었지만 leetCode의 경우 복잡하게 만들지 말자

class Solution
// Working perfect in Terminal
// but runtime error inclusive range error

  List<int> twoSum(List<int> nums, int target) {
    List<int> result = <int>[];
    for (var i = 0; i < nums.length; i++) {
      int complement = target - nums[i];
      var index = nums.indexOf(complement, i + 1);
      if (nums[index] + nums[i] == target) {
        return result = [i, index];
      }
      break;
    }
    return result;
  }
}




// to keep track on the index
extension SubScript<T> on List<T>{
T? operator [](int index)=> length > index ? elementAt(index) : null;
}

좋은 웹페이지 즐겨찾기