1. 两数之和


1. 两数之和

    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) &#123;
            for (int j = i + 1; j < n; ++j) &#123;
                if (nums[i] + nums[j] == target) &#123;
                    return new int[]&#123;i, j&#125;;
                &#125;
            &#125;
        &#125;
        return new int[0];
    &#125;

    public int[] twoSum2(int[] nums, int target) &#123;
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) &#123;
            if (hashtable.containsKey(target - nums[i])) &#123;
                return new int[]&#123;hashtable.get(target - nums[i]), i&#125;;
            &#125;
            hashtable.put(nums[i], i);
        &#125;
        return new int[0];
    &#125;


//链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/

&#125;

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
459. 重复的子字符串 459. 重复的子字符串
https://leetcode-cn.com/problems/repeated-substring-pattern/solution/zhong-fu-de-zi-zi-fu-chuan-by-leetcode-solution/ 45
2021-02-27 future
下一篇 
136. 只出现一次的数字 136. 只出现一次的数字
136. 只出现一次的数字难度简单 1712给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?示例 1:输入: [2,
2021-02-27 future
  目录