用 null 替换数组中的重复字符串而不复制数组和硬编码数组长度

时间:2021-05-09 10:44:58

标签: java

我正在尝试:

  1. 创建大小为 N 的字符串数组
  2. 要求用户填写姓名
  3. 删除重复项并用空值替换
  4. 打印出相同顺序的数组

解决方案是在最外层循环中将索引 import wget import csv with open('cache.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: wget.download(', '.join(row)) 处的单词取出到单独的 i 变量中,以便在设置数组条目后也可以将其与每个其他单词进行比较在索引 String 处为 null。 – 奥莱 V.V.

问题是: 有没有可能以更好、更优化的方式解决这个问题?

i

5 个答案:

答案 0 :(得分:1)

只需重写 Uzair 代码。兄弟 你做了一件了不起的工作。只是不同也可以

 Scanner sc = new Scanner(System.in);
       List<String> strings = new ArrayList<>() ;
       List<String> result = new ArrayList<>();
       int arraySize = 4;
        for (int i = 0; i <arraySize ; i++) {
            strings.add(sc.nextLine());
        }
    result = strings.stream().distinct();

答案 1 :(得分:1)

这个解决方案相当于我之前的答案,它只使用数组。 它隐藏了 java LinkedHashSet 实现背后的先前答案的复杂性:

import java.util.Scanner;
import java.util.Arrays;
import java.util.LinkedHashSet

public class DeleteEquals {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arrSize = 10;
        Set<String> result = new LinkedHashSet<>()

        for (int i = 0; i < arrSize; i++) {
            String check = sc.nextLine();
            if (check != null) {
              result.add(sc.nextLine());
            }
        }
        result.forEach(System.out::println);
    }
}

正如评论中提到的,由于 HashSet 的实现,重复项将被删除,并且需要 O(n * log n) 时间。通过使用 LinkedHashSet,您可以保存用户提供的值的顺序。

如果你需要更底层的解决方案,只需要数组(+一个临时映射),那么请看我之前的回答

答案 2 :(得分:1)

你可以这样做:

Scanner sc = new Scanner(System.in);
int n = 3;

Set<String> distinctStrings = IntStream.range(0, n)
        .mapToObj(i -> sc.nextLine())
        .collect(Collectors.toSet());

System.out.println(distinctStrings);

输入:

Westbrook
Jordan
Westbrook

输出:

[Jordan, Westbrook]

答案 3 :(得分:0)

它将在给定的输入字符串中获得不同的值。过滤掉重复的字符串。

      Scanner sc = new Scanner(System.in);
   List<String> strings = new ArrayList<>() ;
   List<String> result = new ArrayList<>();
   int arraySize = 4;
    for (int i = 0; i <arraySize ; i++) {
        strings.add(sc.nextLine());
    }
 result =  strings.stream()
.filter(e -> Collections.frequency(strings, e) >= 1)
.distinct()
.collect(Collectors.toList());
 System.out.print("After Removing Duplicated Value:\n ");
 result.stream().forEach(System.out::println);
<块引用>

输出

Output

答案 4 :(得分:0)

此解决方案仅使用数组:

import java.util.Scanner;
import java.util.Arrays;

public class DeleteEquals {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arrSize = 10;
        String[] sortedResult = new String[arrSize];
        String[] result = new String[arrSize];
        Map<String, Integer> originalIndexMap = new HashMap<>();

        for (int i = 0; i < arrSize; i++) {
            String currentResult = sc.nextLine();
            sortedResult[i] = currentResult;
            if (originalIndexMap.get(currentResult) == null) {
              //store the index of the first appearance of currentResult
              originalIndexMap.put(currentResult, i);
            }
        }

        //sorting array with "quicksort" to reduce the time to find the duplicates (time will be O(n * log n) with quicksort)
        Arrays.sort(sortedResult);
        String previousResult = null;
        for (int i = 0; i < arrSize; i++) {
          String currentResult = sortedResult[i];
          if (currentResult != null && currentResult != previousResult) {
            //currentResult is unique because of the sorting
            previousResult = currentResult;
            //originalIndexMap stores the index of the first appearance of the currentResult string. We should store currentResult by the index of the first appearance to preserve user input order
            result[originalIndexMap.get(currentResult)] = currentResult;
          } else {
             //duplicate or null: ignore it
          }
        }

        for (int i = 0; i < arrSize; i++) {
          //with originalIndexMap we preserve the order of the user input in the result array
          String currentResult = result[i];
          if (currentResult != null) {
            System.out.println(currentResult);
          } else {
            //null value corresponds to null or duplicate value in the original result: should be ignored
          }            
        }
    }
}

由于在 java.util.Arrays 中实现了 Arrays.sort()(它们默认使用“quicksort”),该解决方案将具有 O(n * log n) 时间函数。

我们必须使用 4 次迭代:

 1. first iteration will initialise sortedResult and originalIndexMap
 2. second iteration will sort the elements in the sortedResult, using Arrays.sort()
 3. third iteration will remove duplicates and insert unique not-null elements in result array by putting it at the index of the first appearance of the element in the user input
 4. fourth iteration will output result array, ignoring null values, which correspond to null or duplicate elements in the original input

所以如果元素的数量是 n,这个算法将需要:

1. (3 * n) elements in stack memory
2. O(n) time in the first iteration
3. O(n log n) time for sorting array
4. O(n log n) time for storing elements to result array (map search gives us O(log n) for each element here)
5. O(n) for result output

该算法的总时间函数为O(n) + O(n log n) + O(n log n) + O(n),相当于O(n log n)

该算法的总内存占用相当于 3n

相关问题