3.15蓝桥杯练习

题目1

代码:

package test_3_15;

public class test1 {
    public static int majorityElement(int[] nums) {
            int count = 0;
            int result = 0;
            for(int i=0;i<nums.length;i++){
                for (int j = 0; j < nums.length; j++) {
                    if(i == j){
                        continue;
                    }
                    else {
                        if(nums[i] == nums[j]){
                            count += 1;
                        }
                    }
                }
                if(count + 1 > nums.length / 2){
                    result = nums[i];
                    break;
                }
                else {
                    count = 0;
                }
            }
            return result;
    }

    public static void main(String[] args) {
        int[] nums = {2,2,1,1,1,2,2};
        int[] nums1 = {3,2,3};
        System.out.println(majorityElement(nums));
        System.out.println(majorityElement(nums1));
    }
}

运行截图:

猜你喜欢

转载自blog.csdn.net/m0_63911789/article/details/129590678