carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1588:所有奇数长度子数组的和(sum-of-all-odd-length-subarrays) #250

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和。

子数组 定义为原数组中的一个连续子序列。

请你返回 arr 中 所有奇数长度子数组的和 。

  示例 1:

输入:arr = [1,4,2,5,3] 输出:58 解释:所有奇数长度子数组和它们的和为: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4,2] = 7 [4,2,5] = 11 [2,5,3] = 10 [1,4,2,5,3] = 15 我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

示例 2:

输入:arr = [1,2] 输出:3 解释:总共只有 2 个长度为奇数的子数组,[1] 和 [2]。它们的和为 3 。

示例 3:

输入:arr = [10,11,12] 输出:66  

提示:

1 <= arr.length <= 100 1 <= arr[i] <= 1000  

进阶:

你可以设计一个 O(n) 时间复杂度的算法解决此问题吗?

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/sum-of-all-odd-length-subarrays

carloscn commented 1 year ago

问题分析

这个和utils里面打印子数组有点类似: https://github.com/carloscn/structstudy/blob/master/c_programming/utils/utils.c#L231

我们借用打印子数组的思想,用二进制bit位来代表是否输出的子数组的元素。不同的是,我们要生成一个one矩阵,然后根据one矩阵来输出所有的子数组。

pub fn sum_odd_length_subarrays(arr: Vec<i32>) -> i32
{
    if arr.len() < 1 {
        return 0;
    }

    let mut i:usize;
    let mut j:usize;
    let mut k:usize;
    let mut n:usize;
    let mut ret:i32 = 0;
    let mut temp_buffer:Vec<i32> = vec![0; arr.len()];
    let mut ones_format:Vec<usize> = vec![];
    let mut ones_bit_count:usize = 1;

    while ones_bit_count <= arr.len() {
        let mut t = 0;
        i = 0;
        while i < ones_bit_count {
            t = t << 1 | 1;
            i += 1;
        }

        i = 0;
        while i + ones_bit_count - 1 < arr.len() {
            ones_format.push(t << i);
            i += 1;
        }

        ones_bit_count += 2;
    }

    for e in ones_format {
        j = e; k = 0; n = 0;
        while j != 0 {
            if j & 0x1 == 0x1 {
                temp_buffer[n] = arr[k];
                n += 1;
            }
            j >>= 1;
            k += 1;
        }

        for m in 0..n {
            ret += temp_buffer[m];
        }
    }

    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/555531 https://github.com/carloscn/structstudy/commit/e5f4515155e07947cf2ce73a3046f43c70ff93de