• TwoSum


    给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

    您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

    例子:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    我的解决方法:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int solution[] = new int[2];
                for(int i=0; i<nums.length-1; i++){
                    solution[0] = i;
                    for(int j=(i+1); j<nums.length; j++){
                        if((nums[i]+nums[j])==target){
                            solution[1] = j;
                            return solution;
                        }
                    }
                }
                return solution;
        }
    }

    LeetCode解决方法:

    方法一:暴力相加

    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    方法二:双程哈希表

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    方法三:单程哈希表

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
  • 相关阅读:
    jQuery中常用方法和jQuery思维导图
    jQuery
    JS-AJAX and jQuery-AJAX
    Linux系统里导入maven项目
    maven项目里的ssh框架整合
    spring框架的两大核心:IOC和AOP
    JAVA的抽象类和接口
    JAVA面向对象的三大特征
    JAVA---面向对象
    JAVA---方法
  • 原文地址:https://www.cnblogs.com/K-artorias/p/7654531.html
Copyright © 2020-2023  润新知