找出数组中重复的值
public class RepeatBase {
public static int[] num = {1,0,8,4,5,6,2,8,1,6};
public static void main(String[] args) {
// System.out.println(repeatCheckBySet(num));
// System.out.println(repeatCheckByTemp(num));
// System.out.println(repeatCheckByOrderSort(num));
System.out.println(isPowerOfTwo(7));
}
/**
* 时间复杂数为O(n)-线性
* 利用set保存元素的特性,存在-不保存-返回false,不存在-保存-返回true
*
* @param num
* @return
*/
public static int repeatCheckBySet(int[] num) {
//对原数据进行严格校验
if (num == null || num.length == 0) {
return -1;
}
Set<Integer> setCheck = new HashSet<>();
for (int source : num) {
if (!setCheck.add(source)) {
return source;
}
}
return -1;
}
/**
* 借助temp,索引位置累计加一,然后判断是否有重复
*
* @param num
* @return
*/
public static String repeatCheckByTemp(int[] num) {
if (num == null || num.length == 0) {
return "-1";
}
StringBuilder stringBuilder = new StringBuilder();
int[] temp = new int[num.length];
for (int source : num) {
temp[source]++;
if (temp[source] > 1) {
stringBuilder.append(source).append("_");
continue;
}
}
return StringUtils.isBlank(stringBuilder.toString()) ? "-1" : stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
}
/**
* 排序后,进行相邻之间的比较,相等及返回
*
* @param num
* @return
*/
public static int repeatCheckByOrderSort(int[] num) {
if (num == null || num.length == 0) {
return -1;
}
Arrays.sort(num);
int length = num.length;
for (int i = 0; i + 1 < length; i++) {
if (num[i] == num[i + 1]) {
return num[i];
}
}
return -1;
}
/**
* == 优先级高于 &
* 求某个数是否是2的幂等值
*
* @param n
* @return
*/
public static boolean isPowerOfTwo(int n) {
return (n & (n - 1)) == 0;
}
}
缘于生活,而归于工作。本人所书,而意于分享。
如有转载,请注明出处!
--活出自己范儿

浙公网安备 33010602011771号