鍓戞寚 Offer 03. 鏁扮粍涓噸澶嶇殑鏁板瓧
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了鍓戞寚 Offer 03. 鏁扮粍涓噸澶嶇殑鏁板瓧相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e9%87%8d%e5%a4%8d' title='閲嶅'>閲嶅
bre list oid util hashset 娴嬭瘯鐢ㄤ緥 涓暟 imppackage com.example.lettcode.offer;
import java.util.*;
/**
* @Class FindRepeatNumber
* @Description 鍓戞寚 Offer 03. 鏁扮粍涓噸澶嶇殑鏁板瓧
* 鎵惧嚭鏁扮粍涓噸澶嶇殑鏁板瓧銆? * 鍦ㄤ竴涓暱搴︿负 n 鐨勬暟缁?nums 閲岀殑鎵€鏈夋暟瀛楅兘鍦?0锝瀗-1 鐨勮寖鍥村唴銆? * 鏁扮粍涓煇浜涙暟瀛楁槸閲嶅鐨勶紝浣嗕笉鐭ラ亾鏈夊嚑涓暟瀛楅噸澶嶄簡锛屼篃涓嶇煡閬撴瘡涓暟瀛楅噸澶嶄簡鍑犳銆傝鎵惧嚭鏁扮粍涓换鎰忎竴涓噸澶嶇殑鏁板瓧銆? * <p>
* 绀轰緥 1锛? * 杈撳叆锛? * [2, 3, 1, 0, 2, 5, 3]
* 杈撳嚭锛? 鎴?3
* <p>
* 闄愬埗锛? * 2 <= n <= 100000
* @Author
* @Date 2020/6/26
**/
public class FindRepeatNumber {
}
// 瑙f硶1锛氬埄鐢↙ist锛屾椂闂村鏉傚害瓒呮椂
public static int findRepeatNumber(int[] nums) {
List<Integer> integerList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (integerList.contains(nums[i])) {break;}
integerList.add(nums[i]);
}
return -1;
}
// 瑙f硶2锛氬埄鐢⊿et
public static int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
// 瑙f硶3锛氶鐩腑鎻愬埌闀垮害涓?n 鐨勬暟缁?nums 閲岀殑鎵€鏈夋暟瀛楅兘鍦?0锝瀗-1 鐨勮寖鍥村唴銆傛瀯寤轰竴涓瓑闀跨殑鏁扮粍锛屽彧瑕乶um[i]涓轰笅鏍囩殑鍏冪礌鐨勫€间笉涓?锛屽氨璇存槑鏇剧粡鍑虹幇杩?// 鏃堕棿澶嶆潅搴﹀拰绌洪棿澶嶆潅搴﹀潎涓篛(n)
public static int findRepeatNumber(int[] nums) {
int[] temp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (temp[nums[i]] == 0) temp[nums[i]]++;
else return nums[i];
}
return -1;
}
// 娴嬭瘯鐢ㄤ緥
public static void main(String[] args) {
int[] nums = new int[]{2, 3, 1, 0, 2, 5, 3};
int ans = findRepeatNumber(nums);
System.out.println("demo01 result:" + ans);
// leetcode涓婃湁涓祴璇曠敤渚嬮暱搴﹀湪10K宸﹀彸锛屽鏄撹秴鏃?}
以上是关于鍓戞寚 Offer 03. 鏁扮粍涓噸澶嶇殑鏁板瓧的主要内容,如果未能解决你的问题,请参考以下文章