LeetCode题集(2)

442. 数组中重复的数据

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;
    }
}

238. 除自身以外数组的乘积

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;
    }
}

611. 有效三角形的个数

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;
    }
}

560. 和为K的子数组

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值