삭제하려면 어떻게 해야 하는 중복에서는 C#배열?
-
08-06-2019 - |
문제
나와 함께 작업 string[]
편에서는 C#에서는 반환하는 함수에서 호출합니다.수도 캐스팅 Generic
컬렉션,하지만 내가 궁금했을 경우 그것을 할 수있는 더 좋은 방법,아마도를 사용해 임시 배열입니다.
는 가장 좋은 방법은 무엇입하고 중복을 제거하거에서 C#배열?
해결책
가능성이 사용할 수 있습 LINQ 쿼리를 이렇게하려면:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
다른 팁
기 HashSet<string> 방법:
public static string[] RemoveDuplicates(string[] s)
{
HashSet<string> set = new HashSet<string>(s);
string[] result = new string[set.Count];
set.CopyTo(result);
return result;
}
불행하게도 이 솔루션은 또한이 필요합니다..NET framework3.5 이상으로 HashSet 되지 않았 추가될 때까지는 버전입니다.수도 있습 사용 배열입니다.유(), 기능의 LINQ.
하는 데 필요한 경우 정렬,그것을 구현할 수 있습니다 류는 것 또한 중복을 제거합.
두 마리를 죽이고 하나의 돌,다음입니다.
다음과 같은 테스트와 작동 코드를 것이 중복 제거에서 배열입니다.을 포함해야 합니다 시스템입니다.컬렉션 네임스페이스가 있습니다.
string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};
var sList = new ArrayList();
for (int i = 0; i < sArray.Length; i++) {
if (sList.Contains(sArray[i]) == false) {
sList.Add(sArray[i]);
}
}
var sNew = sList.ToArray();
for (int i = 0; i < sNew.Length; i++) {
Console.Write(sNew[i]);
}
할 수 있는 포장이 최대로 기능하고 싶은 경우.
이에 따라 달라질 수 있습니다 어떻게 당신이 원하는 엔지니어링 솔루션을 경우 배열을 수 없는 큰 당신에 대해 걱정하지 않는 목록을 정렬할 수 있습을 시도해 무언가가 다음과 같습니다.
public string[] RemoveDuplicates(string[] myList) {
System.Collections.ArrayList newList = new System.Collections.ArrayList();
foreach (string str in myList)
if (!newList.Contains(str))
newList.Add(str);
return (string[])newList.ToArray(typeof(string));
}
-이 면접 질문 물었다.지금 나는 그의 코딩이다.
static void Main(string[] args)
{
int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 };
int numDups = 0, prevIndex = 0;
for (int i = 0; i < array.Length; i++)
{
bool foundDup = false;
for (int j = 0; j < i; j++)
{
if (array[i] == array[j])
{
foundDup = true;
numDups++; // Increment means Count for Duplicate found in array.
break;
}
}
if (foundDup == false)
{
array[prevIndex] = array[i];
prevIndex++;
}
}
// Just Duplicate records replce by zero.
for (int k = 1; k <= numDups; k++)
{
array[array.Length - k] = '\0';
}
Console.WriteLine("Console program for Remove duplicates from array.");
Console.Read();
}
List<String> myStringList = new List<string>(); foreach (string s in myStringArray) { if (!myStringList.Contains(s)) { myStringList.Add(s); } }
이 O(n^2), 되지 않는 문제에 대한 짧은 목록이 될 것으로 채우는 콤보 하지만 될 수 있는 빠르게 되는 문제에 큰 컬렉션입니다.
protected void Page_Load(object sender, EventArgs e)
{
string a = "a;b;c;d;e;v";
string[] b = a.Split(';');
string[] c = b.Distinct().ToArray();
if (b.Length != c.Length)
{
for (int i = 0; i < b.Length; i++)
{
try
{
if (b[i].ToString() != c[i].ToString())
{
Response.Write("Found duplicate " + b[i].ToString());
return;
}
}
catch (Exception ex)
{
Response.Write("Found duplicate " + b[i].ToString());
return;
}
}
}
else
{
Response.Write("No duplicate ");
}
}
기 O(n*n) 접근 방법을 사용하는 O(1) 공간입니다.
void removeDuplicates(char* strIn)
{
int numDups = 0, prevIndex = 0;
if(NULL != strIn && *strIn != '\0')
{
int len = strlen(strIn);
for(int i = 0; i < len; i++)
{
bool foundDup = false;
for(int j = 0; j < i; j++)
{
if(strIn[j] == strIn[i])
{
foundDup = true;
numDups++;
break;
}
}
if(foundDup == false)
{
strIn[prevIndex] = strIn[i];
prevIndex++;
}
}
strIn[len-numDups] = '\0';
}
}
이 hash/linq 방법 위에는 무엇이 당신이 일반적으로 실생활에서 사용.그러나 인터뷰에서 그들은 일반적으로 일부 제약 조건을 예를 들어일정한 공간을 규칙 해시 또는 내부 api -는 규칙을 사용하여 LINQ.
추가 모든 문자열을 사전에 키를 얻을 수 있는 시설습니다.이것은 생산을 각각의 고유 한 문자열하지만,반드시 같은 순서로 원래의 입력했습니다.
이 필요한 경우 최종 결과 같은 순서로 원래의 입력,고려할 때 처음 발생의 각 문자열을 사용하여 다음과 같은 알고리즘을 대신:
- 목록을 가지고(최종 출력)고전(중복 항목을 확인하려면)
- 각 문자열을 입력이 존재하는지 확인하십시오에서 이미 사전
- 하지 않을 경우,추가 그것을 모두 사전 목록
끝에,목록에 포함하는 첫 번째 발생 각자의 독특한 문자열입니다.
는 것이 있는지 확인하십시오 같은 것들을 문화와 이러한 구성할 때 사전에 당신을 확인하는 손잡이 중복으로 편지를 강조습니다.
다음과 같은 조각의 코드를 시도하고 중복을 제거하거에서 ArrayList 지만 이것은 최적의 솔루션을 제공합니다.나는 이 질문하는 동안 인터뷰하고 중복을 제거하거를 통해 재귀,그리고 사용하지 않고 두 번째/temp arraylist:
private void RemoveDuplicate()
{
ArrayList dataArray = new ArrayList(5);
dataArray.Add("1");
dataArray.Add("1");
dataArray.Add("6");
dataArray.Add("6");
dataArray.Add("6");
dataArray.Add("3");
dataArray.Add("6");
dataArray.Add("4");
dataArray.Add("5");
dataArray.Add("4");
dataArray.Add("1");
dataArray.Sort();
GetDistinctArrayList(dataArray, 0);
}
private void GetDistinctArrayList(ArrayList arr, int idx)
{
int count = 0;
if (idx >= arr.Count) return;
string val = arr[idx].ToString();
foreach (String s in arr)
{
if (s.Equals(arr[idx]))
{
count++;
}
}
if (count > 1)
{
arr.Remove(val);
GetDistinctArrayList(arr, idx);
}
else
{
idx += 1;
GetDistinctArrayList(arr, idx);
}
}
어쩌면 hashset 는 저장하지 않는 요소 중복하고 자동으로 무시하는 요구를 추가 중복.
static void Main()
{
string textWithDuplicates = "aaabbcccggg";
Console.WriteLine(textWithDuplicates.Count());
var letters = new HashSet<char>(textWithDuplicates);
Console.WriteLine(letters.Count());
foreach (char c in letters) Console.Write(c);
Console.WriteLine("");
int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
Console.WriteLine(array.Count());
var distinctArray = new HashSet<int>(array);
Console.WriteLine(distinctArray.Count());
foreach (int i in distinctArray) Console.Write(i + ",");
}
참고:지 않을 테스트!
string[] test(string[] myStringArray)
{
List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
if (!myStringList.Contains(s))
{
myStringList.Add(s);
}
}
return myStringList.ToString();
}
이 필요 할 수도...
편집 아!!!구타하여 강탈해 분!
테스트 및 작동합니다.어떤 멋진 것은 이 문화에 민감도 검색
class RemoveDuplicatesInString
{
public static String RemoveDups(String origString)
{
String outString = null;
int readIndex = 0;
CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
if(String.IsNullOrEmpty(origString))
{
return outString;
}
foreach (var ch in origString)
{
if (readIndex == 0)
{
outString = String.Concat(ch);
readIndex++;
continue;
}
if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)
{
//Unique char as this char wasn't found earlier.
outString = String.Concat(outString, ch);
}
readIndex++;
}
return outString;
}
static void Main(string[] args)
{
String inputString = "aAbcefc";
String outputString;
outputString = RemoveDups(inputString);
Console.WriteLine(outputString);
}
}
--AptSenSDET
이 코드 100%제거 중복되는 값 배열에서[내가 사용되는 a[i]].....변환할 수 있습니다 그것이 어떤 OO 언어입니다.....:)
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(a[i] == a[j])
{
for(int k=j;k<size;k++)
{
a[k]=a[k+1];
}
j--;
size--;
}
}
}
간단한 해결책:
using System.Linq;
...
public static int[] Distinct(int[] handles)
{
return handles.ToList().Distinct().ToArray();
}
일반적인 확장 방법:
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
HashSet<TSource> set = new HashSet<TSource>(comparer);
foreach (TSource item in source)
{
if (set.Add(item))
{
yield return item;
}
}
}
할 수 있 이 코드를 사용하는 경우 ArrayList
ArrayList arrayList;
//Add some Members :)
arrayList.Add("ali");
arrayList.Add("hadi");
arrayList.Add("ali");
//Remove duplicates from array
for (int i = 0; i < arrayList.Count; i++)
{
for (int j = i + 1; j < arrayList.Count ; j++)
if (arrayList[i].ToString() == arrayList[j].ToString())
arrayList.Remove(arrayList[j]);
public static int RemoveDuplicates(ref int[] array)
{
int size = array.Length;
// if 0 or 1, return 0 or 1:
if (size < 2) {
return size;
}
int current = 0;
for (int candidate = 1; candidate < size; ++candidate) {
if (array[current] != array[candidate]) {
array[++current] = array[candidate];
}
}
// index to count conversion:
return ++current;
}
아래 간단한 논리에서는 자바를 통과 배열의 요소를 두고 있다면 같은 요소 할당하 제로 그것은 플러스 당신은 당신을 만지지 않는 인덱스의 요소를 비교.
import java.util.*;
class removeDuplicate{
int [] y ;
public removeDuplicate(int[] array){
y=array;
for(int b=0;b<y.length;b++){
int temp = y[b];
for(int v=0;v<y.length;v++){
if( b!=v && temp==y[v]){
y[v]=0;
}
}
}
}
private static string[] distinct(string[] inputArray)
{
bool alreadyExists;
string[] outputArray = new string[] {};
for (int i = 0; i < inputArray.Length; i++)
{
alreadyExists = false;
for (int j = 0; j < outputArray.Length; j++)
{
if (inputArray[i] == outputArray[j])
alreadyExists = true;
}
if (alreadyExists==false)
{
Array.Resize<string>(ref outputArray, outputArray.Length + 1);
outputArray[outputArray.Length-1] = inputArray[i];
}
}
return outputArray;
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };
List<int> updatedlist= removeduplicate(listofint1);
foreach(int num in updatedlist)
Console.WriteLine(num);
}
public static List<int> removeduplicate(List<int> listofint)
{
List<int> listofintwithoutduplicate= new List<int>();
foreach(var num in listofint)
{
if(!listofintwithoutduplicate.Any(p=>p==num))
{
listofintwithoutduplicate.Add(num);
}
}
return listofintwithoutduplicate;
}
}
}