LeetCode之路——LeetCode_1_TwoSum

来源:互联网 发布:阿里云 国际版 编辑:程序博客网 时间:2024/06/07 01:05

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 thesame element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解决方案一(39ms):直接两个for循环,直到找到两个数之和为指定值(略)

解决方案二(11ms):用一个类的数组存储数组的元素与对应下标,将其排序,声明一个左索引,初始值为0,一个右索引,初始值为数组长度-1,如果左右索引对应值之和大于目标数,右索引-1,如果小于,左索引+1,直到等于,返回左右索引对应的原数组索引值的数组形式。
public class Solution{
   class temp implements Comparable<temp>{  //声明一个类 保存数组的元素以及对应下标,通过Comparable接口实现排序
        int index;
        int val;
        
        temp(int index,int val){
            this.index = index;
            this.val = val;
        }

        public int compareTo(temp o) {
            if(this.val < o.val)
                return -1;
            return 1;
        }
        
    }
 public int[] twoSum(int[] a,int index){
        
        temp[] T = new temp[a.length];
        
         for(int i =0;i< a.length;i++){    //将数组保存到temp类的数组里
             temp t = new temp(i,a[i]);    
             T[i] = t;
         }
        
         Arrays.sort(T);   //将temp类的数组排序
         int l = 0;
         int r = a.length - 1;
        
         while(T[l].val + T[r].val != index){   //比较左右索引对应元素之和(停止循环条件:等于目标数)
            
             if(T[l].val + T[r].val < index) // 如果小了,左索引右移一位
                 l++;
             if(T[l].val + T[r].val > index)  //如果大了,右索引左移一位
                 r--;
            
         }

        int[] res = {T[l].index,T[r].index};
        
         return res;
    }

}


原创粉丝点击