LC442. 数组中重复的数据
class Solution {
public List<Integer> findDuplicates(int[] nums) {
//排序后
List<Integer> list = new ArrayList();
if(nums.length == 0 || nums.length == 1)
return list;
Arrays.sort(nums);
int n = nums.length;
int cur = 1;
while(cur < n){
if(nums[cur - 1] == nums[cur]){
list.add(nums[cur]);
}
cur += 1;
}
return list;
}
}
LC120. 三角形最小路径和
//动态规划,从最后一行往上递推上去即可。因为只用到了下一行的dp[i + 1][j]和dp[i + 1][j + 1]所以不需要定义N行一行即可。
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[][] dp = new int[n + 1][n + 1];
for(int i = n - 1;i >= 0;i--){
for(int j = 0;j <= i;j++){
dp[i][j] = Math.min(dp[i+1][j],dp[i + 1][j + 1]) + triangle.get(i).get(j);
}
}
return dp[0][0];
}
}
//优化版本空间复杂度为O(N)
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[] dp = new int[n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
}
}
return dp[0];
}
}
剑指 Offer 53 - I. 在排序数组中查找数字 I
//定义一个函数也就是寻找右侧边界值,采用[left,mid - 1][mid + 1,right]的模板,变更细节处,返回的下标值就是target右侧边界的下一位!!!
class Solution {
public int search(int[] nums, int target) {
return helper(nums,target) - helper(nums,target - 1);
}
public int helper(int[] nums,int target){
int i = 0,j = nums.length - 1;
while(i <= j){
int mid = (i + j) / 2;
if(target >= nums[mid]){
i = mid + 1;
}else{
j = mid - 1;
}
}
return i;
}
}