[LeetCode] 001.Two Sum (Java)

Problem description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Input

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

Code

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

Analysis

过于简单不分析。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,106评论 0 23
  • 本文转自:风轻云淡 AngularJS之页面跳转Route 除了引用AngularJs.js外,还要引用路由JS,...
    大热天晒太阳阅读 532评论 0 0
  • 永生是极需要勇气的吧… 看着生活过尽千帆,看着亲近的人相继离去…如若存在轮回,还要一遍又一遍地相遇,别离…独自在爱...
    豆沙杯子喵小姐阅读 253评论 0 0
  • 世界万物都有生命,而你在意过的你生命吗? 每个人的一生说短不短,说长也不长。有的人今日复明日,明日复后日,可你有真...
    L痴梦阅读 196评论 0 0