从数组中删除左侧重复项

huangapple go评论74阅读模式
英文:

Removing left sided duplicates from array

问题

public static int[] solve(int[] arr) {
    ArrayList<Integer> result = new ArrayList<>(); // Using ArrayList to collect non-duplicate values
    
    for (int i = arr.length - 1; i >= 0; i--) { // Loop from the end of the array
        if (!result.contains(arr[i])) { // Check if the value is not already in the result
            result.add(arr[i]); // Add the value to the result
        }
    }
    
    int[] arr2 = new int[result.size()]; // Create the final array
    for (int i = result.size() - 1; i >= 0; i--) {
        arr2[result.size() - 1 - i] = result.get(i); // Copy values from result ArrayList to arr2
    }
    
    return arr2; // Return the array without left duplicates
}

这是修复后的代码,用于从输入数组中移除左侧重复项(保留最后一个重复项)。这个代码段会创建一个新的 ArrayList,从原数组末尾开始遍历,将非重复的值添加到 ArrayList 中。然后,它会将 ArrayList 中的值复制到一个新的数组中,以满足返回数组的要求。

英文:

I'm trying to find mistakes in my code and i wonder if you could help me. My task is to write a method that would take an array as an input and return this array without left duplicates(last numbers stay). My code doesn't work in case when input is( 1,2,1,2,1,2,3 ) It returns (1, 1, 2, 3) instead of 1,2,3. Here is the code

     public static int [] solve(int [] arr){
          boolean check=false;
        ArrayList&lt;Integer&gt; test = new ArrayList&lt;&gt;(); // idk how to compete this task without ArrayList
          for (int i = 0; i &lt; arr.length; i++) { // Here i pass my array to ArrayList
             test.add(arr[i]);
             }
             
            while(check==false) {
                for (int i = 0; i &lt; test.size(); i++) {
                   for (int j = i + 1; j &lt; test.size(); j++) { // Somewhere here must be my mistake that i can&#39;t find 
                       check=true;
                       if (test.get(i) == test.get(j)) {
                           test.remove(i);
                          check=false;
                       }
                   }
               }
           }
      // i created second array to return array without duplcates. 
           int arr2[];
             arr2=new int[test.size()];
             for(int i=0;i&lt;arr2.length;i++){
                 arr2[i]=test.get(i);
             }
        
        return arr2;
    
       }
     }

I tried to complete this task on my own, so i didnt use Google to get help until now. If you know how to improve my code feel free to change everything you want to. Thank you in advance!

答案1

得分: 4

HashSet可以实现这一点,因为你不能将重复元素放入HashSet,你只需要将数组放入HashSet即可。

List<Integer> arr2 = new ArrayList<>(new HashSet<>(arr));
英文:

HashSet can do this since you cant put duplicate elements to HashSet, all you need to do is put your array into HashSet.

List&lt;Integer&gt; arr2 = new ArrayList&lt;&gt;(new HashSet&lt;&gt;(arr));

答案2

得分: 2

你可以创建第二个列表,遍历输入列表,并针对输入列表的每个元素检查第二个列表是否包含它。如果不包含,则将其添加到第二个列表中。这样可以通过你在原始帖子中提到的测试案例:

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        List<Integer> test = new ArrayList<>();
        List<Integer> noduplicates = new ArrayList<>();
        test.add(1);
        test.add(2);
        test.add(1);
        test.add(2);
        test.add(1);
        test.add(2);
        test.add(3);
      
        for (Integer i : test) {
            if (!noduplicates.contains(i)) {
                noduplicates.add(i);
            }
        }
        System.out.println(noduplicates);
    }
}
英文:

You can create a second list, iterate through your input list and for each element of your input list check if the second list contains it. If it doesn't, add it to the second list. This passes the test case that you mention in your original post:

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
      List&lt;Integer&gt; test = new ArrayList&lt;&gt;();
      List&lt;Integer&gt; noduplicates = new ArrayList&lt;&gt;();
      test.add(1);
      test.add(2);
      test.add(1);
      test.add(2);
      test.add(1);
      test.add(2);
      test.add(3);
      
      for (Integer i : test) {
          if (!noduplicates.contains(i)) {
              noduplicates.add(i);
          }
      }
      System.out.println(noduplicates);
    }
}

答案3

得分: 2

以下是翻译好的部分:

简单的方法是

1. 将数组的数字以相反的顺序添加到`LinkedHashSet`以保留唯一的数字并保留每个唯一数字的最后一个条目
2. 使用`LinkedHashSet`创建一个`List`。
3. 使用`Collections#reverse`反转`List`。

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<Integer> set = new LinkedHashSet<>();
        int[] arr = { 7, 7, 4, 5, 7, 2, 7 };

        // 将数组的数字以相反的顺序添加到LinkedHashSet中,以删除重复项并保留每个唯一数字的最后一个条目。
        for (int i = arr.length - 1; i >= 0; i--) {
            set.add(arr[i]);
        }

        // 使用LinkedHashSet创建一个List
        List<Integer> list = new ArrayList<>(set);

        // 反转List
        Collections.reverse(list);

        // 显示结果
        System.out.println(list);
    }
}

输出:

[4, 5, 2, 7]
英文:

A simple way will be to

  1. Add the numbers of the array in reverse order to a LinkedHashSet in order to keep only unique numbers as well as to preserve the last entry of each unique number.

  2. Create a List out of the LinkedHashSet.

  3. Reverse the List using Collections#reverse.

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Set;
    
    public class Main {
    	public static void main(String[] args) {
    		Set&lt;Integer&gt; set = new LinkedHashSet&lt;&gt;();
    		int[] arr = { 7, 7, 4, 5, 7, 2, 7 };
    
    		// Add the numbers of the array in reverse order to a LinkedHashSet in order to remove
    		// duplicates as well as to preserve the last entry of each unique number.
    		for (int i = arr.length - 1; i &gt;= 0; i--) {
    			set.add(arr[i]);
    		}
    
    		// Create a List out of the LinkedHashSet
    		List&lt;Integer&gt; list = new ArrayList&lt;&gt;(set);
    
    		// Reverse the List
    		Collections.reverse(list);
    
    		// Display the result
    		System.out.println(list);
    	}
    }
    

Output:

[4, 5, 2, 7]

答案4

得分: 0

截至即将推出的 Java 21 版本,可以使用 LinkedHashSet 的新添加的 addLast(e) 方法。

public static int[] solve(int[] arr) {
    SequencedSet<Integer> set = new LinkedHashSet<>();
    for (int i : arr) {
        set.addLast(i);
    }
    return set.stream().mapToInt(Integer::intValue).toArray();
}

LinkedHashSet 是一个集合类,它不允许重复项(因为它是一个 Set),同时保留顺序(因为它是一个 SequencedCollection)。addLast 方法会将给定的项目添加到集合的末尾,如果它尚未存在,或者将其移到末尾(如果它已经存在)。

英文:

As of the upcoming Java 21, a LinkedHashSet can be used with its newly added addLast(e) method.

public static int[] solve(int[] arr) {
    SequencedSet&lt;Integer&gt; set = new LinkedHashSet&lt;&gt;();
    for (int i : arr) {
        set.addLast(i);
    }
    return set.stream().mapToInt(Integer::intValue).toArray();
}

LinkedHashSet is a collection class which disallows duplicates (due to being a Set) while preserving order (due to being a SequencedCollection). The addLast method adds the given item to the end of the set if it isn't already present, or moves it to the end if it is.

huangapple
  • 本文由 发表于 2020年8月18日 05:18:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63458798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定