zoukankan      html  css  js  c++  java
  • leetcode two sum

    two sum

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    twosum
    • 方案一使用哈希表
    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap();
            for(int i = 0; i<nums.length; i++){
                map.put(nums[i], i);
            }
            for (int i = 0; i < nums.length; i++) {
                int complement = target - nums[i];
                if (map.containsKey(complement) && map.get(complement) != i) {
                    return new int[] { i, map.get(complement) };
                }
            }
            return null;
        }
    }
    
    • 方案二快排
    class Solution {
        public int[] twoSum(int[] nums, int target) {
    
    		// corner cases
    		if (nums == null || nums.length <= 1) {
    			return null;
    		}
    		int[] nums2 = Arrays.copyOf(nums, nums.length);
    		Arrays.sort(nums);
    		int left = 0;
    		int right = nums.length - 1;
    		int a = 0;
    		int b = 0;
    		while (left < right) {
    			long sum = (long) nums[left] + (long) nums[right];
    			if (sum == target) {
    				a = nums[left];
    				b = nums[right];
    				break;
    			} else if (sum < target) {
    				left += 1;
    			} else {
    				right -= 1;
    			}
    		}
    		// find index 1
    		for(int i = 0; i < nums2.length; i++){
    			if(nums2[i] == a) {
    				left = i;
    				break;
    			}
    		}
    		// find index 2
    		for(int i = nums2.length - 1; i >= 0; i--){
    			if(nums2[i] == b) {
    				right = i;
    				break;
    			}
    		}
    		return new int[]{Math.min(left, right),Math.max(left, right)};
    
    
        }
    }
    
  • 相关阅读:
    大数据基础---Spark累加器与广播变量
    大数据基础---Spark部署模式与作业提交
    大数据基础---Spark_Transformation和Action算子
    大数据基础---Spark_RDD
    大数据基础---Spark开发环境搭建
    大数据基础---Spark简介
    利用numpy 计算信息量
    三调地类分级字典
    省/直辖市行政区代码表
    设置 Jupyter notebook 运行的浏览器
  • 原文地址:https://www.cnblogs.com/Dyleaf/p/7965720.html
Copyright © 2011-2022 走看看