zoukankan      html  css  js  c++  java
  • 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

    代码:

    import java.util.HashMap;
    
    public class TwoSum {
    
        public static void main(String[] args) {
            int[] sums = { 3, 2, 4 };
            int target = 6;
            int[] res = twoSum(sums, target);
            int[] indexs = getTwoIndexs(sums,target);
            for (int i = 0; i < res.length; i++) {
                System.out.println(res[i]);
            }
            for (int i = 0; i < indexs.length; i++) {
                System.out.println(indexs[i]);
            }
        }
    
        // HashMap的解决方式,参考了网上的,又学习了HashMap
        private static int[] getTwoIndexs(int[] nums, int target) {
            int[] twoIndexs = new int[2];
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(nums[i])) {
                    int index = map.get(nums[i]);
                    twoIndexs[0] = Math.min(i+1, index+1);
                    twoIndexs[1] = Math.max(i+1, index+1);
                    break;
                }
                int value = target - nums[i];
                map.put(value, i);
            }
            return twoIndexs;
        }
    
        // 之前自己写的解决方式,明显不好
        private static int[] twoSum(int[] nums, int target) {
            int[] res = new int[2];
            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[i] + nums[j] == target) {
                        res[0] = i + 1;
                        res[1] = j + 1;
                    }
                }
            }
            return res;
        }
    
    }
  • 相关阅读:
    转战博客园
    C++虐恋:MBCS安装失败导致的四天误工
    Servlet 3.0 新特性详解 (转载)
    数据库连接池proxool的两种使用方式
    java异常处理中的细节
    InvocationTargetException异常的深入研究-servlet的setAttribute与getAttribute
    如果我是一个全栈极客,那么,下一步该怎么走?
    C++基础与提高 001
    用户及文件权限管理
    命令行操作体验
  • 原文地址:https://www.cnblogs.com/tf-Y/p/4868663.html
Copyright © 2011-2022 走看看