• 1. 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

    链接: http://leetcode.com/problems/two-sum/

    题解:

    使用HashMap,一次遍历数组。 

    Time Complexity - O(n),Space Complexity - O(n)

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int result[] = {-1, -1};
            if(numbers == null || numbers.length == 0)
                return result;
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for(int i = 0; i < numbers.length; i++){
                if(!map.containsKey(target - numbers[i]))
                    map.put(numbers[i], i);
                else{
                    result[0] = map.get(target - numbers[i]) + 1;
                    result[1] = i + 1;
                    break;
               }    
            }
            return result;
        }
    }

    或者可以先sort数组,再用双指针找target - numbers[i]。这样的话Time Complexity 应该是是O(nlogn), Space Complexity是O(n),就是时间复杂度换空间复杂度。 要注意sort之后原数组的index也会改变,要找到好的方法保存原数组的index。

    Python:

    Time Complexity - O(n), Space Complexity - O(n)

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if len(nums) <= 1:
                return False
            dict = {}
            
            for i, num in enumerate(nums):
                if target - num in dict:
                    return dict[target - num] + 1, i + 1
                else:
                    dict[num] = i
    
            return -1, -1

    Update:

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if (nums is None) or (len(nums) < 2):
                return -1, -1
            dict = {}
            
            for i, num in enumerate(nums):
                if target - num in dict:
                    return dict[target - num] + 1, i + 1
                else:
                    dict[num] = i
            
            return -1, -1
            

    二刷: 

    Java: 

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = new int[] {-1, -1};
            if (nums == null || nums.length == 0) {
                return res;
            }
            Map<Integer, Integer> map = new HashMap<>();
            
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(target - nums[i])) {
                    res[0] = map.get(target - nums[i]) + 1;
                    res[1] = i + 1;
                    return res;
                } else {
                    map.put(nums[i], i);
                }
            }
            
            return res;
        }
    }

    Python:

    发现检测元素是否在dict中用 in dict比用in dict.keys()快十倍,不清楚为什么

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict = {}
            for i, num in enumerate(nums):
                if target - num in dict:
                    return (dict[target - num] + 1, i + 1)
                else:
                    dict[num] = i
            return (-1, -1)
                    
                    

    三刷:

    3/7/2016. 

    有可能要考虑一下正负数的溢出

    Java:

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = new int[2];
            if (nums == null || nums.length == 0) {
                return res;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(target - nums[i])) {
                    res[0] = map.get(target - nums[i]);
                    res[1] = i;
                    return res;
                }
                map.put(nums[i], i);
            }
            return res;
        }
    }

    Reference:

    http://www.cnblogs.com/springfor/p/3859618.html

  • 相关阅读:
    java 21
    maven POM.xml 标签详解
    shell sed 替代1
    lua的table库中的常用函数总结
    Lua字符串及模式匹配
    lua文件读写
    qt添加lua支持
    关于c调用lua 对‘luaL_newstate()’未定义的引用的问题解决办法
    Lua开发环境
    linux安装lua相关编译报错
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4427946.html
Copyright © 2020-2023  润新知