zoukankan      html  css  js  c++  java
  • leetcode -Two Sum

    链接:https://leetcode.com/problems/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

    给出数组numbers 和数字target, 找出数组中两个元素之和为target的元素位置(数组的下标是1-based,即1为第一个元素)。

    思路1:使用两层循环,判断满足numers[i]+numbers[j]==target的i和j 。这里时间复杂度是o(n^2)

    思路2:使用HashMap,Map的key为numbers中的所有元素,value为元素对应的下标位置。遍历一次数组,如果numbers[i]+某数target,那么target-numbers[i]一定在数组中,即Map.get(某数)一定存在值,并且jMap.get(某数)。这样一次遍历就可以找到相对应的两个元素位置。

    代码:

     public int[] twoSum(int[] nums, int target) {
            int index[] = new int[2];
            int len = nums.length;
            HashMap map = new HashMap<Integer, Integer>();
            for (int i = 0; i < len; i++) {
                map.put(nums[i], i + 1);
            }
            for (int i = 0; i < len; i++) {
                index[0] = i + 1;
                int val1 = nums[i];
                int val2 = target - val1;
                if (map.get(val2) != null) {
                    index[1] = (Integer) map.get(val2);
                    if(index[0]==index[1])
                    {
                        continue;
                    }
                    return index;
                }
            }
            return index;
        }
    
  • 相关阅读:
    mongodb常用命令(转)
    C++位运算详解(转)
    C++Vector用法(转)
    php下载文件
    二维数组和指针(转)
    php数据采集(转)
    通过PHP实现浏览器点击下载TXT文档(转)
    Linux 文件颜色的含义
    如何在Linux下创建与解压zip, tar, tar.gz和tar.bz2文件【转】
    X11VNC:让Windows可以远程管理Ubuntu桌面
  • 原文地址:https://www.cnblogs.com/limingluzhu/p/4896859.html
Copyright © 2011-2022 走看看