Two Sum系列

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.

样例:

numbers=[2, 7, 11, 15], target=9
return [1, 2]

代码实现:

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length == 0) {
            return new int[0];
        }
        Map<Integer, Integer> map = new HashMap<>();
   //     List<Integer> list = new ArrayList<>();
     //   Arrays.sort(numbers);
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                int[] result = {map.get(numbers[i])+1, i+1};
                return result;
              //  list.add(map.get(numbers[i]));
                //list.add(i+1);
            } else {
                map.put(target-numbers[i], i);
            }
        }
        int[] result = {};
        return result;
    }
}

Two Sum - Greater than target

题目:

Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs.

样例:

numbers = [2, 7, 11, 15], target = 24. 
Return 1. (11 + 15 is the only pair)

代码实现:

public class Solution {
    /**
     * @param nums: an array of integer
     * @param target: an integer
     * @return: an integer
     */
    public int twoSum2(int[] nums, int target) {
        // Write your code here
        if (nums == null || nums.length < 2) {
            return 0;
        }
        Arrays.sort(nums); 
        int left = 0;
        right = nums.length - 1;
        int count = 0;
        while (left < right) {
            if (nums[left] + nums[right] <= target) {
                left++;
            } else {
                count += right - left;
                right--;
            }
        }  
        return count;
    }
}

Two Sum - Data structure design

题目:

Design and implement a TwoSum class. It should support the following operations: add and find.

  • add - Add the number to an internal data structure.
  • find - Find if there exists any pair of numbers which sum is equal to the value.

样例 :

add(1); add(3); add(5);
find(4) // return true
find(7) // return false

代码实现:

public class TwoSum {
    private List<Integer> list = null;
    private Map<Integer, Integer> map = null;
    public TwoSum() {
        list = new ArrayList<Integer>();
        map = new HashMap<Integer, Integer>();
    }

    // Add the number to an internal data structure.
    public void add(int number) {
        if (map.containsKey(number)) {
            map.put(number, map.get(number)+1);
        } else {
            map.put(number, 1);
            list.add(number);
        }
    }

    // Find if there exists any pair of numbers which sum is equal to the value.
    public boolean find(int value) {
        for (int i = 0; i < list.size(); i++) {
            int num1 = list.get(i), num2 = value - num1;
            if ((num1 == num2 && map.get(num1) > 1)
                || (num1 != num2 && map.containsKey(num2))) {  
                return true;
                }
            }
        return false;
    }
}


// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);

Two Sum - Input array is sorted

题目:

Given an array of integers that is already sorted in ascending order, 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.

样例 :

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

代码实现:

public class Solution {
    /*
     * @param nums an array of Integer
     * @param target = nums[index1] + nums[index2]
     * @return [index1 + 1, index2 + 1] (index1 < index2)
     * 
     * Two-Pointers
     */
    public int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while (left < right) {
            if (nums[left] + nums[right] == target) {
                int[] result = new int[2];
                result[0] = left + 1;
                result[1] = right +1;
                return result;
            } else if (nums[left] + nums[right] < target) {
                left++;
            } else {
                right--;
            }
        }
        int[] result = {};
        return result;
    }
}

Two Sum - Unique pairs

题目:

Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target number. Please return the number of pairs.

样例:

Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47 
2 + 45 = 47

代码实现:

public class Solution {
    /**
     * @param nums an array of integer
     * @param target an integer
     * @return an integer
     */
    public int twoSum6(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return 0;
        }
        int left = 0;
        int right = nums.length-1;
        int count = 0;
        Arrays.sort(nums);
        while (left < right) {
            if (nums[left]+nums[right] == target) {
                count++;
                left++;
                right--;
                while(left < right && nums[left] == nums[left-1]) {
                    left++;
                }
                while(left < right && nums[right] == nums[right+1]) {
                    right--;
                }
            } else if (nums[left]+nums[right] > target) {
                right--;
            } else {
                left++;
            }
        }
        return count;
    }
}

Two Sum - Closest to target

题目:

Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target.
Return the difference between the sum of the two integers and the target.

样例 :

nums = [-1, 2, 1, -4],target = 4.
最接近值为 1

代码实现:

public class Solution {
    /**
     * @param nums an integer array
     * @param target an integer
     * @return the difference between the sum and the target
     */
    public int twoSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return -1;
        }
        Arrays.sort(nums);
        int left = 0;
        int right = nums.length-1;
        int diff = Integer.MAX_VALUE;
        while (left < right) {
            if (nums[left] + nums[right] < target) {
                diff = Math.min(diff, target-nums[left]-nums[right]);
                left++;
            } else {
                diff = Math.min(diff, nums[left]+nums[right]-target);
                right--;
            }
        }
        return diff;
    }
}

Two Sum-Less than or Equal to target

题目:

Given an array of integers, find how many pairs in the array such that their sum is less than or equal to a specific target number. Please return the number of pairs.

样例:

Given nums = [2, 7, 11, 15], target = 24. 
Return 5. 
2 + 7 < 24
2 + 11 < 24
2 + 15 < 24
7 + 11 < 24
7 + 15 < 25

代码实现:

public class Solution {
    /**
     * @param nums an array of integer
     * @param target an integer
     * @return an integer
     */
    public int twoSum5(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return 0;
        }
        Arrays.sort(nums);
        int left = 0;
        int right = nums.length-1;
        int count = 0;
        while (left < right) {
            while (left < right && nums[left] + nums[right] > target) {
                right--;
            } 
            while (left < right && nums[left] + nums[right] <= target) {
                count += right - start;
                left++;  
            } 
        }
        return count;
    }
}

Two Sum - Difference equals to target

题目:

Given an array of integers, find two numbers that their difference equals to a target value.
where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.

样例:

nums = [2, 7, 15, 24], target = 5
return [1, 2] (7 - 2 = 5)

代码实现:

class Pair {
    int idx;
    int num;
    public Pair(int i, int num) {
        this.idx = i;
        this.num =num;
    }
}
public class Solution {
    /*
     * @param nums an array of Integer
     * @param target an integer
     * @return [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum7(int[] nums, int target) {
                int[] indexs = new int[2];
        if (nums == null || nums.length < 2)
            return indexs;

        if (target < 0)
            target = -target;

        int n = nums.length;
        Pair[] pairs = new Pair[n];
        for (int i = 0; i < n; ++i)
            pairs[i] = new Pair(i, nums[i]);

        Arrays.sort(pairs, new Comparator<Pair>(){
            public int compare(Pair p1, Pair p2){
                return p1.num - p2.num;
            } 
        });

        int j = 0;
        for (int i = 0; i < n; ++i) {
            if (i == j)
                j ++;
            while (j < n && pairs[j].num - pairs[i].num < target)
                j ++;

            if (j < n && pairs[j].num - pairs[i].num == target) {
                indexs[0] = pairs[i].idx + 1;
                indexs[1] = pairs[j].idx + 1;
                if (indexs[0] > indexs[1]) {
                    int temp = indexs[0];
                    indexs[0] = indexs[1];
                    indexs[1] = temp;
                }
                return indexs;
            }
        }
        return indexs;

    }
}

Three-Sum

题目:

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

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

样例:

S = {-1 0 1 2 -1 -4}, A solution set is:
(-1, 0, 1)
(-1, -1, 2)

代码实现:

public class Solution {
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
        ArrayList<ArrayList<Integer>> results = new ArrayList<>();
        // 存在相同的数,则不再加入target
        if (numbers == null || numbers.length < 3) {
            return results;
        }
        Arrays.sort(numbers);
        /*遍历数组,取一个数的相反数做target
        *i < numbers.length-2 保留最后2个,twoSum
        */
        for (int i = 0; i < numbers.length; i++) {
            if (i > 0 && numbers[i] == numbers[i-1]) {
                continue;
            }
            int left = i+1;
            int right = numbers.length-1;
            int target = -numbers[i];
            twoSum(numbers, left, right,target, results);
        }
        return results;
    }
    private void twoSum(int[] numbers,
                        int left,
                        int right,
                        int target,
                        ArrayList<ArrayList<Integer>> results) {
        while (left < right) {
            if (numbers[left]+numbers[right] == target) {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(-target);
                list.add(numbers[left]);
                list.add(numbers[right]);
                left++;
                right--;
                results.add(list);
                // 去除重复加入的情况
                while (left < right && numbers[left] == numbers[left-1]) {
                    left++;
                }
                while (left < right && numbers[right] == numbers[right+1]) {
                    right--;
                }
            } else if (numbers[left]+numbers[right] > target) {
                right--;
            } else {
                left++;
            }
        }                        
    }
}

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.

样例:

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 {
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target : An integer
     * @return : return the sum of the three integers, the sum closest target.
     */
    public int threeSumClosest(int[] numbers, int target) {
        if (numbers == null || numbers.length < 3) {
            return -1;
        }
        Arrays.sort(numbers);
        int bestSum = numbers[0]+numbers[1]+numbers[2];
        for (int i = 0; i < numbers.length; i++) {
            int left = i+1;
            int right = numbers.length-1;
            while(left < right) {
                int sum = numbers[i]+numbers[left]+numbers[right];
                if (Math.abs(sum-target) < Math.abs(bestSum-target)) {
                    bestSum = sum;
                } 
                if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }            
        return bestSum;
    }
}

Four-Sum

题目:

给一个包含 n 个数的整数数组 S,在 S 中找到所有使得和为给定整数 target 的四元组 (a, b, c, d)。
注意事项

  • 四元组 (a, b, c, d) 中,需要满足 a <= b <= c <= d
  • 答案中不可以包含重复的四元组。

样例:

例如,对于给定的整数数组 S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)

代码实现:

public class Solution {
    /**
     * @param numbers : Give an array numbersbers of n integer
     * @param target : you need to find four elements that's sum of target
     * @return : Find all unique quadruplets in the array which gives the sum of
     *           zero.
     */
    public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        Arrays.sort(numbers);
        //选择第一个数
        for (int i = 0; i < numbers.length - 3; i++) {
            //避免选择重复的数
            if (i != 0 && numbers[i] == numbers[i-1]) {
                continue;
            }
            //选择第二个数
            for (int j = i+1; j < numbers.length - 2; j++) {
                //避免选择重复的数
                //if (j != 0 && numbers[j] == numbers[j-1]) {
                //j的取值应该依i而定
                if (j != i+1 && numbers[j] == numbers[j-1]) {
                    continue;
                }
                int left = j+1;
                int right = numbers.length-1;
                while (left < right) {
                    int sum = numbers[i] + numbers[j] + numbers[left] + numbers[right];
                    if (sum < target) {
                        left++;
                    } else if (sum > target) {
                        right--;
                    } else {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(numbers[i]);
                        list.add(numbers[j]);
                        list.add(numbers[left]);
                        list.add(numbers[right]);
                        result.add(list);
                        left++;
                        right--;
                        //避免3、4加入重复的数
                        while (numbers[left] == numbers[left-1]) {
                            left++;
                        }
                        while (numbers[right] == numbers[right+1]) {
                            right--;
                        }
                    }
                }
             }
        }
        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容