LeetCode16,17

LeetCode 第16,17题的分析和总结

LeetCode 16. 3Sum Closest

描述:

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

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路:

3Sum 变形题目,使用绝对值表示离目标值的远和近

代码:

public int threeSumClosest_copy(int[] num,int target) {
	int result = num[0]+num[1]+num[num.length-1];
	Arrays.parallelSort(num);
	int small = num[0]+num[1]+num[2];
	if(small >= target) return small;
	int big = num[num.length-3]+num[num.length-2]+num[num.length-1];
	if(big <= target) return big;

	for (int i = 0; i < num.length - 2; i++) {
    int start = i + 1, end = num.length - 1;
    while (start < end) {
        int sum = num[i] + num[start] + num[end];
        if (sum > target) {
            end--;
        } else {
            start++;
        }
        if (Math.abs(sum - target) < Math.abs(result - target)) {
            result = sum;
        }
    }
 }
 return result;
}

LeetCode 17. Letter Combinations of a Phone Number

题目描述:

Given a string containing digits from 2-9 inclusive,
return all possible letter combinations
that the number could represent.

A mapping of digit to letters
(just like on the telephone buttons)
is given below.
 Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd",
"be", "bf", "cd", "ce", "cf"].
Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

思路:

集合和排序的变种

代码:

public List<String> letterCombinations(String digits) {
	LinkedList<String> ans = new LinkedList<String>();
	if(digits.isEmpty()) return ans;
	String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
	ans.add("");
	for(int i =0; i<digits.length();i++){
		int x = Character.getNumericValue(digits.charAt(i));
		while(ans.peek().length()==i){
			String t = ans.remove();
			for(char s : mapping[x].toCharArray())
				ans.add(t+s);
		}
	}
	return ans;
}

这里使用了迭代的思路,但是用的非常的优雅,首先是遍历给出的digits每一位的数字, 然后利用队列或者栈的先进先出的原则,循环的遍历已经组合完成的数组,添加上后来的数据,比较的巧妙和优雅。

Powered by andiHappy and Theme by AndiHappy