LeetCode 001 Two Sum - Java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 001 Two Sum - Java相关的知识,希望对你有一定的参考价值。

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.

Example:

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

 

定位:简单题
对于目标值,我们对原数组进行遍历,对于其中每个数字,再遍历后面所有,计算每两个数字之和,当等于目标值时返回。

 

Java实现:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int len=nums.length;
 4         for(int i=0;i<len-1;i++){
 5             for(int j=i+1;j<len;j++){
 6                 if(nums[i]+nums[j]==target){
 7                     return new int[]{i,j};
 8                 }
 9             }
10         }
11         return new int[0];
12     }
13 }

以上是关于LeetCode 001 Two Sum - Java的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode刷题记录001Two Sum

LeetCode 001 Two Sum - Java

LeetCode OJ_题解(python):001-Two Sum ArrayEasy

LeetCode #001# Two Sum详解(js描述)

LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

LeetCode-数组篇 1 Two Sum