LeetCode14,15

LeetCode 第14,15题的分析和总结

LeetCode 14. Longest Common Prefix

描述:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

思路:

遍历寻找即可

代码:

public String longestCommonPrefix_copy(String[] strs) {
  if(strs == null || strs.length == 0) return "";
  if(strs.length == 1) return strs[0];
  int from = 0;boolean flag = true;
  int end = strs[0].length();
  String tmp = strs[0];
  for(;from < end && flag;from++) {
    for(int j = 1;j<strs.length;j++) {
      if(from >= strs[j].length() || strs[j].charAt(from) != tmp.charAt(from)) {
        flag=false;
        from = from-1;
        break;
      }
    }
  }

  return tmp.substring(0, from);
}

LeetCode:15. 3Sum

题目描述:

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

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

思路:

首先是排序,拍好了续,才能够使用“双指针的方法”,最后注意相等的值的处理

代码:

/***
 * 关键在于nums的先排序
 * 然后两头堵的方式,from =0,end = length-1 , 中间的sum = sumvalue- (from+end)
 * 循环的条件是先确定匹配值i(0 到 length-1),然后去(i+1,i+2,。。。length-1 中寻找from 和 end)
 */
public List<List<Integer>> threeSum(int[] nums) {
	List<List<Integer>> res = new ArrayList<List<Integer>>();
	Arrays.sort(nums);
	for (int i = 0; i < nums.length - 2; i++) {
		if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
			int from = i + 1;
			int end = nums.length - 1;
			int sumt = 0 - nums[i];
			while (from < end) {
				int temp = nums[from] + nums[end];
				if (sumt == temp) {
					res.add(Arrays.asList(nums[i], nums[from], nums[end]));

					while (from < end && from + 1 < nums.length && nums[from] == nums[from + 1])
						from++;
					while (from < end && end + 1 < nums.length && nums[end] == nums[end + 1])
						end--;

					from++;
					end--;
				} else if (sumt < temp) {
					end--;
				} else {
					from++;
				}
			}
	}
}
	return res;
}

Powered by andiHappy and Theme by AndiHappy