ITPub博客

首页 > 应用开发 > Java > Two Sum

Two Sum

原创 Java 作者:壹頁書 时间:2017-08-03 11:24:42 0 删除 编辑

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].


https://leetcode.com/problems/two-sum/description/

我想出来的办法,简单粗暴


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

另附网上的一段代码,优雅很多

  1. class Solution {
  2.     public int[] twoSum(int[] nums, int target) {
  3.         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

  4.         for (int i = 0; i < nums.length; i++) {
  5.             if (map.get(nums[i]) != null) {
  6.                 int[] result = { map.get(nums[i]), i };
  7.                 return result;
  8.             }
  9.             map.put(target - nums[i], i);
  10.         }

  11.         int[] result = {};
  12.         return result;

  13.     }
  14. }



 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2143018/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: Reverse Integer
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339901