【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】

【001-Two Sum(求两个数的和)】

原题

  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开始的。你可以假设每一个输入肯定只有一个结果。

解题思路

  创建一个辅助类数组,对辅助类进行排序,使用两个指针,开始时分别指向数组的两端,看这两个下标对应的值是否等于目标值,如果等于就从辅助类中找出记录的下标,构造好返回结果,返回。如果大于就让右边的下标向左移,进入下一次匹配,如果小于就让左边的下标向右移动,进入下一次匹配,直到所有的数据都处理完

代码实现

import java.util.Arrays;

public class Solution {
    /**
     * 辅助类
     */
    private static class Node implements Comparable<Node> {
        int val; // 值
        int idx; // 值对应的数组下标

        public Node() {
        }

        public Node(int val, int idx) {
            this.val = val;
            this.idx = idx;
        }

        // 比较方法
        @Override
        public int compareTo(Node o) {
            if (o == null) {
                return -1;
            }
            return this.val - o.val;
        }
    }

    /**
     * 001-Two Sum(求两个数的和) 
     * 
     * @param nums   输入数组
     * @param target 两个数相加的和
     * @return 两个数对应的下标
    public int[] twoSum(int[] nums, int target) {
        // 用于保存返回结果
        int[] result = {0, 0};

        // 创建辅助数组
        Node[] tmp = new Node[nums.length];
        for (int i = 0; i < nums.length; i++) {
            tmp[i] = new Node(nums[i], i);
        }

        // 对辅助数组进行排序
        Arrays.sort(tmp);

        // 记录辅助数组中左边一个值的下标
        int lo = 0;
        // 记录辅助数组中右边一个值的下标
        int hi = nums.length - 1;

        // 从两边向中间靠陇进行求解
        while (lo < hi) {
            // 如果找到结果就设置返回结果,并且退出循环
            if (tmp[lo].val + tmp[hi].val == target) {

                if (tmp[lo].idx > tmp[hi].idx) {
                    result[0] = tmp[hi].idx + 1;
                    result[1] = tmp[lo].idx + 1;
                } else {
                    result[0] = tmp[lo].idx + 1;
                    result[1] = tmp[hi].idx + 1;
                }
                break;
            }
            // 如果大于目标值,右边的下标向左移动
            else if (tmp[lo].val + tmp[hi].val > target) {
                hi--;
            }
            // 如果小于目标值,左边的下标向右移动
            else {
                lo++;
            }
        }
        return result;
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

《【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】》

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/DERRANTCM/article/details/46905233

    原文作者:derrantcm
    原文地址: https://blog.csdn.net/derrantcm/article/details/46905233
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞