日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode: Single Number

發(fā)布時間:2023/12/9 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode: Single Number 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Given an array of integers, every element appears twice except for one. Find that single one.Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Analysis: 需求里面要求O(N)時間以及無額外空間,這就排除了使用boolean array, hashmap這些個方法,只能在原數(shù)組上進行查找。O(N)基本上就相當(dāng)于遍歷數(shù)組.

最好的方法:

1 public class Solution { 2 public int singleNumber(int[] nums) { 3 int res = 0; 4 for(int i = 0 ; i < nums.length; i++){ 5 res ^= nums[i]; 6 } 7 return res; 8 } 9 }

第二遍做法: 17行 & 運算符優(yōu)先等級低于 == 所以一定要打括號

1 public class Solution { 2 public int singleNumber(int[] A) { 3 int[] check = new int[32]; 4 int res = 0; 5 for (int i=0; i<A.length; i++) { 6 for (int j=0; j<32; j++) { 7 if ((A[i]>>j & 1) == 1) { 8 check[j]++; 9 } 10 } 11 } 12 for (int k=0; k<32; k++) { 13 if (check[k] % 2 == 1) { 14 res |= 1<<k; 15 } 16 } 17 return res; 18 } 19 }

一樣的思路另一個做法:

1 public int singleNumber(int[] A) { 2 int[] digits = new int[32]; 3 for(int i=0;i<32;i++) 4 { 5 for(int j=0;j<A.length;j++) 6 { 7 digits[i] += (A[j]>>i)&1; 8 } 9 } 10 int res = 0; 11 for(int i=0;i<32;i++) 12 { 13 res += (digits[i]%2)<<i; 14 } 15 return res; 16 }

?另外注意位運算符的優(yōu)先級等級:

1 ()?[]?. 從左到右 2 !?+(正) ?-(負(fù))?~?++?-- 從右向左 3 *?/?% 從左向右 4 +(加)?-(減) 從左向右 5 <<?>>?>>> 從左向右 6 <?<=?>?>=?instanceof 從左向右 7 ==?? != 從左向右 8 &(按位與) 從左向右 9 ^ 從左向右 10 | 從左向右 11 && 從左向右 12 || 從左向右 13 ?: 從右向左 14 =?+=?-=?*=?/=?%=?&=?|=?^= ?~= ?<<=?>>=?? >>>= 從右向左

轉(zhuǎn)載于:https://www.cnblogs.com/EdwardLiu/p/3795723.html

總結(jié)

以上是生活随笔為你收集整理的Leetcode: Single Number的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。