2 Sum ,3 Sum, 3 Sum close

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

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        if(nums == null || nums.length == 0) return res;
        HashMap<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;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}

3 Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0 ; i < nums.length - 2; i++){
            List<Integer> list = new ArrayList<>();
            int left = i + 1;
            int right = nums.length -1;
            int sum =  0 - nums[i];
            while(left < right){
                if(nums[left] + nums[right] == sum){
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    if(!res.contains(list))
                        res.add(new ArrayList<>(list));
                    list.clear();
                    while(left < right && nums[left] == nums[left+1]) left++;
                    while(left < right && nums[right] == nums[right-1]) right--;
                    left++;
                    right--;
                }
                else if(nums[left] + nums[right] < sum){
                    left ++;
                }
                else
                    right--;
            }
        }
        return res;
    }
}

16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
      Arrays.sort(nums);
      int min = Integer.MAX_VALUE;
      for(int i = 0 ;  i < nums.length -2; i++){
          int left = i + 1;
          int right = nums.length - 1;
          int value = target - nums[i];
            while(left < right){
                if(nums[left] + nums[right] == value)
                    return target;

                if(min == Integer.MAX_VALUE || Math.abs(nums[i] + nums[left] + nums[right] - target) < Math.abs(min - target))
                    min = nums[i] + nums[left] + nums[right];

                if(nums[left] + nums[right] > value)
                    right --;

                else
                    left++ ;
                }
            }

      return min;
    }
}
时间: 2024-08-29 11:30:19

2 Sum ,3 Sum, 3 Sum close的相关文章

js中sum(2)(3)(4)返回9和sum(2,3)和sum(2)(3)都返回5并要求扩展性

网上有很多关于sum(1)(2)(3),sum(1,2,3)之类的面试题要求输出相同的结果6并要求可以满足扩展,即有多个参数时也能符合题设的要求,所以自己写了部分例子可以大概满足这些面试题的要求 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><

[leetcode] 303. Range Sum Query &amp;&amp; 304. Range Sum Query 2D - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array do

[LeetCode] Range Sum Query - Immutable &amp; Range Sum Query 2D - Immutable

Range Sum Query - Immutable Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You

29.Combination Sum(和为sum的组合)

Level: ??Medium 题目描述: Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from

[动态规划] Sum游戏 ( Game of Sum, Uva 10891 )

抓住状态转移方程即可   :  从子序列 i j 中取最大 =  i + 从子序列i+1,j中取最大        或         j +  从子序列i,j-1中取最大 #include <algorithm> #include <cstring> #include <cstdio> using namespace std; const int maxn = 100+10; int S[maxn], A[maxn], d[maxn][maxn], vis[maxn]

[email&#160;protected] [303/304] Range Sum Query - Immutable / Range Sum Query 2D - Immutable

https://leetcode.com/problems/range-sum-query-immutable/ class NumArray { public: vector<int> vec; public: NumArray(vector<int> &nums) { if(nums.empty()) return; else { vec.push_back(nums[0]); for(int i=1;i<nums.size();++i) vec.push_bac

LeetCode 303. Range Sum Query - Immutable

求数组nums[i,j]的和 思路:另开一sum数组,sum[i]为nums[0,i]的和,所以nums[i,j] = sum[j] - sum[i-1] 1 class NumArray { 2 public: 3 vector<int> sum; 4 NumArray(vector<int> &nums) { 5 sum.resize(nums.size(), 0); 6 sum[0] = nums[0]; 7 int len = nums.size(); 8 for(

HDU 5586 Sum

最大子串和 #include<cstdio> #include<cstring> const int maxn=100000+10; int n; int x[maxn]; int fx[maxn]; int a[maxn]; int sum[maxn]; int L[maxn],R[maxn]; const int INF=0x7FFFFFFF; int max(int a,int b) { if(a>b) return a; return b; } int main()

Path Sum

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int indicator = 0; public: void check(TreeNode *root

HDU 1003 Max Sum

题目: Problem Description Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14. Input The first line of the input cont