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;
        }
    
  • 相关阅读:
    在路上(转)
    我,机器
    梧桐道上
    傅盛:如何快慢“炼”金山?(转)
    [JS]笔记15之客户端存储cookie
    [JS]笔记14之事件委托
    [JS]笔记13之Date对象
    将博客搬至CSDN
    [JS]笔记12之事件机制--事件冒泡和捕获--事件监听--阻止事件传播
    [JS]笔记11之正则表达式
  • 原文地址:https://www.cnblogs.com/limingluzhu/p/4896859.html
Copyright © 2011-2022 走看看