数组剔除元素后的乘积

给定一个整数数组A。

定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法。

样例

给出A=[1, 2, 3],返回 B为[6, 3, 2]



public class Solution {
    /**
     * @param A: Given an integers array A
     * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
     */
    public ArrayList<Long> productExcludeItself(ArrayList<Integer> A) {
        ArrayList<Long> res = new ArrayList<Long>();
         if (A==null || A.size()==0) return res;
         long[] lProduct = new long[A.size()];
         long[] rProduct = new long[A.size()];
         lProduct[0] = 1;
         for (int i=1; i<A.size(); i++) {
             lProduct[i] = lProduct[i-1]*A.get(i-1);
         }
         rProduct[A.size()-1] = 1;
         for (int j=A.size()-2; j>=0; j--) {
             rProduct[j] = rProduct[j+1]*A.get(j+1);
         }
         for (int k=0; k<A.size(); k++) {
             res.add(lProduct[k] * rProduct[k]);
         }
         return res;
    }
}


在 C# 中,去除数组中的重复元素可以通过多种方式实现。以下是几种常见的方法及其详细说明: ### 方法一:使用 HashSet `HashSet<T>` 是一种集合类型的数据结构,在内部实现了哈希表机制,因此不允许存储重复的键值。通过将其与数组结合使用,可以轻松地过滤掉重复项。 #### 示例代码: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { int[] originalArray = { 1, 2, 3, 4, 5, 3, 2 }; // 使用 HashSet 去重 var hashSet = new HashSet<int>(originalArray); int[] resultArray = hashSet.ToArray(); Console.WriteLine(string.Join(", ", resultArray)); // 输出: 1, 2, 3, 4, 5 } } ``` 这种方法效率较高,因为 `HashSet` 的插入时间复杂度接近 O(1)[^3]。 ### 方法二:借助 LINQ 查询 LINQ(Language Integrated Query)提供了强大的查询能力,其中 `.Distinct()` 方法可以直接用于移除数组内的重复条目。 #### 示例代码: ```csharp using System; using System.Linq; class Program { static void Main() { int[] arrayWithDuplicates = { 10, 20, 10, 30, 20 }; // 利用 Distinct 函数去重 var uniqueElements = arrayWithDuplicates.Distinct().ToArray(); Console.WriteLine(string.Join(", ", uniqueElements)); // 输出: 10, 20, 30 } } ``` 这种方式简洁明了,适合快速开发场景下应用[^2]。 ### 方法三:手动遍历筛选 对于某些特定需或性能优化场合,也可能需要自己编写循环逻辑来完成这项任务。 #### 示例代码: ```csharp using System; class Program { static void Main() { char[] letters = {'a','b','c','d','e','f','g','h','i','j','k'}; bool[] flags = new bool[letters.Length]; Array.Clear(flags, 0, flags.Length); foreach(var letter in letters){ if(Array.Exists(letters,(current)=>flags[current-'a']&&letter==current)){ continue; }else{ flags[letter - 'a']=true; } } // 构建最终无重复版本 string output=""; for(int i=0;i<flags.Length;i++)if(flags[i])output+=Convert.ToChar(i+'a'); Console.Write(output); // 可能输出 abcdefghijklmnopqrstuvwxyz的一部分取决于输入 } } ``` 虽然这段伪代码稍显冗长且针对字符型做了特殊处理,但它展示了另一种思路——即通过标志位记录哪些项目已经被访问过从而达到排除副本的目的[^1]。 综上所述,推荐优先采用基于框架特性的解决方案如 Method One 或 Two ,除非有特别的理由才考虑自定义算法路径 Three 。每种方案都有各自的优劣之处,请依据实际情况选取最合适的那一个。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值