WenJieWangFlyToWorld

导航

LeetCode 1. Two Sum

1. Two Sum

Question

  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 sameelement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

 

Solution

  1. /** 
  2.  * @ClassName Solution 
  3.  * @Description TODO 
  4.  * @Author wangwenjie 
  5.  * @Date 2019/1/23 14:02 
  6.  **/  
  7. public class Solution {  
  8.   
  9.     public  int[] twoSum(int[] nums, int target) {  
  10.         int [] res = new int[2];  
  11.         int num = nums.length;  
  12.         for (int i=0;i<num-1;i++){  
  13.             for (int j = i+1;j<num;j++){  
  14.                 if (nums[i]+nums[j]== target){  
  15.                     res[0] = i;  
  16.                     res[1] = j;  
  17.                     break;  
  18.                 }  
  19.             }  
  20.         }  
  21.   
  22.         return res;  
  23.     }  
  24. }  

posted on 2019-01-30 09:16  WenjieWangFlyToWorld  阅读(98)  评论(0编辑  收藏  举报