165. 比较版本号【中等】
https://leetcode-cn.com/problems/compare-version-numbers/
class Solution {
public int compareVersion(String version1, String version2) {
int m = version1.length(), n = version2.length();
for(int i = 0, j = 0; i < m || j < n; i++,j++) {
int v1 = 0, v2 = 0;
while(i < m && version1.charAt(i) != '.') {
v1 = v1 * 10 + (version1.charAt(i) - '0');
i ++;
}
while(j < n && version2.charAt(j) != '.') {
v2 = v2 * 10 + (version2.charAt(j) - '0');
j ++;
}
if(v1 > v2) return 1;
else if(v1 < v2) return -1;
}
return 0;
}
}
39. 组合总和【中等】
https://leetcode-cn.com/problems/combination-sum/
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, res, path, 0);
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, List<Integer> path, int begin) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(path) );
return;
}
for (int i = begin; i < candidates.length; i++) {
if (candidates[begin] > target)
return;
if (i > 0 && candidates[i] == candidates[i-1]) {
continue;
}
path.add(candidates[i]);
backtrack(candidates, target-candidates[i], res, path, i);
path.remove(path.size() - 1);
}
}
}
162. 寻找峰值【中等】
https://leetcode-cn.com/problems/find-peak-element/
- 只要数组中存在一个元素比相邻元素大,那么沿着它一定可以找到一个峰值
根据上述结论,我们就可以使用二分查找找到峰值。 - 如果 m 较大,则左侧存在峰值,r = m,如果 m + 1 较大,则右侧存在峰值,l = m + 1。
class Solution {
public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid+1])
right = mid;
else if (nums[mid] <= nums[mid+1]) {
left = mid+1;
}
}
return left;
}
}