只出现一次的数字

介绍:给出一个数组,找到这个数组中只出现了一次的"数字"

*这个效率有点差,因为运用了好多循环(不推荐)

执行用时:1367 ms
内存消耗:42.5 MB
public class SingleNumber {
    public static void main(String[] args) {
        int[] nums = {4,1,2,1,2};
        Solution7 solution7 = new Solution7();
        solution7.singleNumber(nums);
    }
}



上面是测试:
//----------------------
下面是分装的代码:


/**
 *
 * 示例 1:
 * 输入: [2,2,1]
 * 输出: 1
 *
 *
 * 示例 2:
 * 输入: [4,1,2,1,2]
 * 输出: 4
 */


class Solution7 {
    public int singleNumber(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - 1 - i; j++) {
                if (nums[j] > nums[j + 1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
        System.out.println("这个数组是: "+Arrays.toString(nums));

        int number = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    number++;
                }
            }
            if (number == 1) {
                System.out.println("这个只出现一次的数字是: " + nums[i]);
                return nums[i];
            }
            number = 0;
        }

        return 1;
    }
}

posted on   陈嘻嘻-  阅读(34)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示