演算法學習–數組

來源:互聯網
上載者:User

   一個數組存放了2n+1個整數,其中有n個數出現了2次,1個數出現了1次,找出出現1次的數是多少?

       //方法一:藉助輔助數組(長度為n+1,元素為一結構體(包含數值和
        //個數兩個成員))進行計數,但是時間複雜度為O(n*n),空間複雜度為O(n+1)

        //本來是想把Val定義為結構體的,但由於結構體是實值型別,不是參考型別,
        //添加到List結合中的元素的屬性值不能被修改,把List中的一個元素賦給另一個Val,修改Val中的value和num,
        //List中對應的Val相關的屬性值是不會改變的,因為他們是記憶體中的兩個不同單元
        //總之:誰叫我C學得不好,用的是C#呢,不然就用C實現了。
    

    public class Val {
public int value;//值
public int num;//出現的次數
}

public int FindA(int[] A, int n)
{
List<Val> list = new List<Val>();
Val val ;
int j=0;
for (int i = 0; i < n ; i++)
{
while (j < n)
{
bool isExist = false;
for(int k=0;k<list.Count;k++)
{
if (list[k].value == A[j])
{
isExist = true;
list[k].num = 2;
break;
}
}

if (!isExist) {
val = new Val();
val.value = A[j];
val.num = 1;
list.Add(val);
}
j++;
}
}

int result = -1;
foreach (Val v in list)
{
if (v.num == 1) {
result = v.value;
break;
}
}
return result;

}

//方法二:藉助一個長度為n/2+1的數組B,如果A中的元素不在B中,就存入B中,
//如果在B中,存在的那個元素後面所有的元素向前移一個單位,相當於去掉這個在B中存在的元素,
//這一進一出的,出現偶數次的都去掉了,只剩下出現奇數次的元素。
public int FindI(int[] A, int n)
{
int[] B = new int[n / 2 + 1];
int k = 0;
for (int i = 0; i < n; i++)
{
bool isExist = false;
for (int j = 0; j <= k; j++)
{
if (A[i] == B[j])
{
isExist = true;
for (int f = j; f < k - 1; f++)
{
B[f] = B[f + 1];
}
k--;
break;
}
}

if (!isExist)
{
B[k] = A[i];
k++;
}
}

return B[0];

}


//方法三:排序。相等的數當然就在一起,單獨的那個數就是那個只出現一次的了,哈哈...
public int FindS(int[] A, int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (A[i] > A[j])
{
int temp = A[j];
A[j] = A[i];
A[i] = temp;
}
}
}

int result = -1;
for (int i = 0; i < n; i = i + 2)
{
if (A[i] != A[i + 1])
{
result = A[i];
break;
}
}
return result;
}



//方法四:異或運算(部落格園這位帥哥牛)
//異或運算 0與任何數異或等於任何數,相等的兩個數異或等於0,
//也就是兩個數對應的二進位位進行異或運算;0^0=0 , 1^0=1 , 0^1=1 , 1^1=0
//出現偶數次都完蛋了,就剩下出現奇數次的了
public int FindSpecial(int[] A, int n)
{
int res = 0;
for (int i = 0; i < n; i++)
{
res = res ^ A[i];
}
return res;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.