輸入是這樣的
100 5
0 10
0 5
75 95
12 17
13 14
并且輸出是65
所以我希望程式計算0-100中的哪些數字不在陣列中。
我就是這樣開始的
static void Main(string[] args)
{
string input1 = Console.ReadLine();
int roadlength = Convert.ToInt32(input1.Split(" ")[0]);
int stagecnt = Convert.ToInt32(input1.Split(" ")[1]);
int[] startpoint = new int[stagecnt];
int[] endpoint = new int[stagecnt];
int km = 0;
for (int i = 0; i < stagecnt; i )
{
string input2 = Console.ReadLine();
startpoint[i] = Convert.ToInt32(input2.Split(' ')[0]);
endpoint[i] = Convert.ToInt32(input2.Split(' ')[1]);
}
for (int i = 0; i < stagecnt; i )
{
uj5u.com熱心網友回復:
讓我們計算范圍內的不同數字,0..100然后從范圍內的總數中減去0..100:
using System.Linq;
...
int[] data = new int[] {
100, 5, 0, 10, 0, 5, 75, 95, 12, 17, 13, 14,
};
...
int min = 0;
int max = 100;
int result = max - min 1 - data
.Where(item => item >= min && item <= max)
.Distinct()
.Count();
uj5u.com熱心網友回復:
你把問題復雜化了,這很簡單。
使用給定范圍初始化陣列/串列。并逐個檢查所有輸入項是否存在于第一個進位中。如果不存在,則只需增加計數。
雖然復雜性很高,但它最簡單的解決方案。
int[] items = ;
int start = 1;
int end = 100;
int[] arr = Enumerable.Range(start, end - start).ToArray();
int count = 0;
for(int i = 0; i < arr.Length; i )
{
if (!items.Contains(arr[i]))
{
count ;
}
}
uj5u.com熱心網友回復:
如果要計算陣列中缺失的整數,與 1 到 100 之間的所有整數相比:
int[] array = {1,2,3,4,5};
HashSet<int> allBetween1And100 = Enumerable.Range(1, 100).ToHashSet();
allBetween1And100.ExceptWith(array); // removes all from the set which are not in array
int countMissing = allBetween1And100.Count; // 95
這種方法的優點是你甚至有一個缺少的集合。當然這需要一些記憶體,所以如果您不需要它們,請選擇一個簡單的回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/528595.html
標籤:C#数组循环数数布尔值
上一篇:for回圈中的JS陣列
