LeetCode 001 Two Sum - Java
阿新 • • 發佈:2017-06-04
兩個 -s sof leet blog 個數 lee class ger
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