Two Sum -- Easy

一、问题描述

  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.

  意思是给定一个数组和目标数,以数组中任意两数之和为目标数的下标作为新数组元素,返回一个数组。

二、生词

  indices    n /'ɪndɪsiːz/ 索引(index的复数)

三、样例及说明

  

四、解题方法

  我首先想到的方法就是暴力破解。。。时间复杂度为O(n^2)

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for(int i = 0; i < nums.length-1; 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         return null;
10     }
11 }

  但是在跟答案的暴力破解相比的话,自己的代码有一个地方没有处理好,就是当没有找到相应的元素时,我返回的是一个null,显然这是不对的(虽然运行的时候没有错误)。

所以应该抛一个异常告诉调用者。

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for(int i = 0; i < nums.length-1; 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         throw new IllegalArgumentException("No two sum solution");
10     }
11 }

猜你喜欢

转载自www.cnblogs.com/crush-u-1214/p/10428046.html
今日推荐