LeetCode0-Two Sum-[Easy]

2263 ワード

postを恥ずかしがるが、勇敢に恥をかく.本シリーズはスラグの成長の道を記録し、目的は主に個人のブラシ問題の構想を総括することである.現在、language:Pythonがデフォルトです.
タイトルDescription:Two Sum
Given an array of integers, returnindicesof the two numbers such that they add up to a specific target. You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice. Example: Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].
考え方1:
遍歴加和.
class Solution(object):
    def twoSum(self, nums, target):
        a = 0;
        while (a < len(nums) ):
            for x in nums:
                for y in nums:
                    result = x + y
                    if (result == target ) & (nums.index(x) <> nums.index(y)):
                        return (nums.index(x),nums.index(y))
                        a = a + 1

結果:Time Limit Exceeded
考え方2:
考え方3の方法を参考にして,インデックスを巡る.
class Solution(object):
   def twoSum(self, nums, target):
           for x in range(len(nums)):
               if target - nums[x] in nums:
                   if x <> nums.index(target - nums[x]):
                       return [x,nums.index(target - nums[x])]

考え方3:(solutionを参照、ソースは図のように)
私はまだこの答えを理解していません......
/**
 *             。    ,       。
 * -                     ,                       。
 * -            :     ,     ,     ,Java        ,Android      ,Big Data      ,
 * -           :http://www.jiuzhang.com/?source=code
 */

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
         numbers=[2, 7, 11, 15],  target=9
         return [1, 2]
     */
    public int[] twoSum(int[] numbers, int target) {
        HashMap map = new HashMap<>();

        for (int i = 0; i < numbers.length; i++) {
            if (map.get(numbers[i]) != null) {
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            map.put(target - numbers[i], i);
        }
        
        int[] result = {};
        return result;
    }
}