class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<Integer>();
int d = nums.length+1;
for(int i=0;i<nums.length;i++)
if(nums[nums[i]%d-1]<=nums.length)
nums[nums[i]%d-1]+=d;
else
ans.add(nums[i]%d);
return ans;
}
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int result[] = new int[nums.length];
int left = 1;
// 从左往右遍历
for(int i = 0; i < nums.length; i++){
result[i] = left;
left = nums[i] * left;
}
int right = 1;
// 从右往左遍历
for(int i = nums.length - 1; i >= 0; i--){
result[i] *= right;
right = nums[i] * right;
}
return result;
}
}
class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
if(n < 3) return 0;
Arrays.sort(nums);
int res = 0;
for(int i = 2;i < n;i++){
int l = 0,r = i - 1;
while(l < r){
while(l < r && nums[l] + nums[r] <= nums[i]) l++;
if(nums[l] + nums[r] > nums[i]){
res += (r - l);
r--;
}
}
}
return res;
}
}
class Solution {
public int subarraySum(int[] nums, int k) {
/**
扫描一遍数组, 使用map记录出现同样的和的次数, 对每个i计算累计和sum并判断map内是否有sum-k
**/
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int sum = 0, ret = 0;
for(int i = 0; i < nums.length; ++i) {
sum += nums[i];
if(map.containsKey(sum-k))
ret += map.get(sum-k);
map.put(sum, map.getOrDefault(sum, 0)+1);
}
return ret;
}
}