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;
        }
    
  • 相关阅读:
    P4855 MloVtry的idea
    CF343D Water Tree
    CF165D Beard Graph
    P3833 [SHOI2012]魔法树
    P2410 [SDOI2009]最优图像 ZKW最大费用最大流
    P2157 [SDOI2009]学校食堂
    P2407 [SDOI2009]地图复原
    P4008 [NOI2003]文本编辑器
    awk里面执行shell命令
    git 系统中 post-receive 钩子不能正常执行 git pull 解决方法
  • 原文地址:https://www.cnblogs.com/limingluzhu/p/4896859.html
Copyright © 2011-2022 走看看