码迷,mamicode.com
首页 > 其他好文 > 详细

求两数之和

时间:2019-08-24 18:46:17      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:ima   turn   比较   返回值   pre   优化   ++   缺点   两数之和   

题目如下:

技术图片

第一次解答:

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

点评:算是比较满意的,但是缺点是如果没有匹配到结果返回值有所不同。合法的结果:【】 我的结果:【0,0】

优化:

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

点评:牺牲空间 new int[0] 来满足合法的格式,此外如果没有匹配到,则不需要额外的 new int[2] 这样的操作

 

 

 

 

求两数之和

标签:ima   turn   比较   返回值   pre   优化   ++   缺点   两数之和   

原文地址:https://www.cnblogs.com/baizhuang/p/11405433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!