LeetCode_001 求两个数的和

来源:互联网 发布:国产网络腐剧 编辑:程序博客网 时间:2024/06/05 18:15

题目

 Given an array of integers, find two numbers such that they add up to a specific target number.
  The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
  You may assume that each input would have exactly one solution.
  Input: numbers={2, 7, 11, 15}, target=9
  Output: index1=1, index2=2

题目解析

 给定一个整数数组,找出其中两个数满足相加等于指定的目标数字。
 函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
注意你返回的结果(包括index1和index2)都不是基于0开始的。可以假设每一个输入肯定只有一个结果。

实现

public class Solution{/**      * 001-Two Sum(求两个数的和)      *      * @param nums   输入数组      * @param target 两个数相加的和      * @return 两个数对应的下标      *      */     public int[] twoSum(int[] nums, int target) {          // 用于保存返回结果          int[] result = {0, 0};          int[] temp_nums = Arrays.copyOfRange(nums,0,nums.length);          // 创建辅助hashmap          HashMap<Integer,Integer> temp_hash = new HashMap<>();          for (int i = 0; i < nums.length; i++) {               temp_hash.put(nums[i],i);          }          //为方便计算对数组进行排序,若不允许对原数组进行改变则创建一个临时数组          Arrays.sort(temp_nums);          // 记录辅助数组的开始下标          int low = 0;          // 记录辅助数组的终止下标          int high = nums.length - 1;          // 从两边向中间靠陇进行求解          while (low < high) {               // 如果找到结果就设置返回结果,并且退出循环               if (temp_nums[low] + temp_nums[high] == target) {                    result[0] = temp_hash.get(temp_nums[low])+1;                    result[1] = temp_hash.get(temp_nums[high])+1;                    if (result[0]>result[1]) {                         int temp = result[0];                         result[0] = result[1];                         result[1] = temp;                    }                    break;               }               // 如果大于目标值               else if (temp_nums[low] + temp_nums[high]> target) {                    high--;               }               // 如果小于目标值               else {                    low++;               }          }          return result;     }}
原创粉丝点击