您的位置:首页 > 其它

leetcode 17-18

2017-09-25 17:39 337 查看

leetcode 17 : Letter Combinations of a Phone Number

问题描述

Given a digit string, 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.



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


分析

这道题是让我们求电话号码对应的所有字母组合,我们可以通过一个队列实现迭代,从头取出长度较短的字符串再加上一个字符添加到队尾。

JAVA代码

public List<String> letterCombinations(String digits) {
LinkedList<String> res = new LinkedList<>();
if(digits.length() == 0) {
return res;
}
//映射关系字符串数组
String[] m = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.add("");
for(int i=0;i<digits.length();i++) {
int x = Character.getNumericValue(digits.charAt(i));
//取得最头的元素长度但不删除元素
while(res.peek().length() == i) {
//移除头元素并赋值给p
String p = res.remove();
for (char c : m[x].toCharArray()) {
//将每一个添加的字符连接到p上并添加到队列尾部
res.add(p+c);
}
}
}
return res;
}


总结

善于灵活应用已有的数据结构的特性,这题就是我们在后面要用前面的数据,所以就利用先进先出的队列解决问题。

leetcode 18 : 4Sum

问题描述

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

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]


分析

这个问题只需要在3Sum的基础上再加一层循环即可,实践复杂度为O(n^3)。

JAVA代码

public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
for(int f=0;f<nums.length-3;f++) {
int subtarget = target - nums[f];
if(f == 0 || nums[f] != nums[f-1]) {
for (int i = f + 1; i < nums.length - 2; i++) {
if (i == f+1 || nums[i] != nums[i - 1]) {
int low = i + 1, high = nums.length - 1, sum = subtarget - nums[i];
while (low < high) {
if (sum == nums[low] + nums[high]) {
res.add(Arrays.asList(nums[f], nums[i], nums[low], nums[high]));
while (low < high && nums[low] == nums[low + 1]) {
low++;
}
while (low < high && nums[high] == nums[high - 1]) {
high--;
}
low++;
high--;
} else if (sum > nums[low] + nums[high]) {
low++;
} else {
high--;
}
}
}
}
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode