如何使用for循环查找给定数组中的最大重复次数

时间:2018-06-08 08:48:09

标签: java

输入:arr[]={4,3,6,6,4,8,1,9,3,6,7,8,6} 输出:6-count (4)

public static int countmaxDuplicate(int arr[]) {
        int maxcount = 0;
        int count = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length - 1; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                }
                if (count > maxcount) {
                    count = maxcount;
                }
            }
        }

        return maxcount;
    }

此代码我试图实现最大重复计数但无法获得解决方案请建议我如何使用for循环获取输出

3 个答案:

答案 0 :(得分:4)

您的代码中存在一些问题

        for (int j = i + 1; j < arr.length; j++) {

        }

        if (count > maxcount) {
                maxcount = count;
        }

另外,您需要在每个阶段重新初始化count

完整版:

public static int countmaxDuplicate(int arr[]) {
    int maxcount = 0;

    for (int i = 0; i < arr.length - 1; i++) {
        int count = 1;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }

        }
        maxcount = Integer.max(maxcount, count);
    }

    return maxcount;
}

您还可以添加布尔数组check以避免重复工作

public static int countmaxDuplicate(int arr[]) {
    int maxcount = 0;
    boolean[]check = new boolean[arr.length];
    for (int i = 0; i < arr.length - 1; i++) {
        if(check[i]){
           continue;
        }
        int count = 1;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) {
                check[j] = true;
                count++;
            }

        }
        maxcount = Integer.max(maxcount, count);
    }

    return maxcount;
}

甚至考虑使用HahsMap,因此这将具有O(n)时间复杂度

HashMap<Integer, Integer> count = new HashMap();
for(int i : arr){
   count.put(i, count.getOrDefault(count, 0) + 1);
}

int maxCount;
for(int i : count.values()){
   maxCount = Integer.max(maxCount, i);
}
return maxCount;

答案 1 :(得分:2)

在inner for循环中,您不是每次都检查最后一个元素。因此,将for循环更改为:

 for (int j = i + 1; j < arr.length ; j++) {
    //your logic
 }

其他错误是您最初将计数初始化为1并且还需要重置计数。你的任务也不对。您保留maxcount作为最终答案,因此您需要更新count而不是public static int countmaxDuplicate(int arr[]) { int maxcount = 1; for (int i = 0; i < arr.length - 1; i++) { int count = 1; for (int j = i + 1; j < arr.length; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxcount) { maxcount= count; } } return maxcount; } 。所以下面的工作将完美无缺。

 package com.example.demo.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.example.demo.Blog;
import com.example.demo.repository.BlogRespository;

import java.util.List;
import java.util.Map;

@RestController
public class BlogController {

    @Autowired
    BlogRespository blogRespository;

    @GetMapping("/blog")
    public List<Blog> index(){
        return blogRespository.findAll();
    }

    @GetMapping("/blog/{id}")
    public Blog show(@PathVariable String id){
        int blogId = Integer.parseInt(id);
        return blogRespository.findById(blogId)
                 .orElseThrow(() -> new IllegalArgumentException(
                 "The requested resultId [" + id +
                 "] does not exist."));
    }

    @PostMapping("/blog/search")
    public List<Blog> search(@RequestBody Map<String, String> body){
        String searchTerm = body.get("text");
        return blogRespository.findByTitleContainingOrContentContaining(searchTerm, searchTerm);
    }

    @PostMapping("/blog")
    public Blog create(@RequestBody Map<String, String> body){
        String title = body.get("title");
        String content = body.get("content");
        return blogRespository.save(new Blog(title, content));
    }

    @PutMapping("/blog/{id}")
    public Blog update(@PathVariable String id, @RequestBody Map<String, String> body){
        int blogId = Integer.parseInt(id);
        // getting blog
        Blog blog = blogRespository.findById(blogId)
             .orElseThrow(() -> new IllegalArgumentException(
             "The requested resultId [" + id +
             "] does not exist."));
        blog.setTitle(body.get("title"));
        blog.setContent(body.get("content"));
        return blogRespository.save(blog);
    }


    @DeleteMapping("blog/{id}")
    public boolean delete(@PathVariable String id){
        int blogId = Integer.parseInt(id);
        blogRespository.delete(blogId);
        return true;
    }


}

答案 2 :(得分:1)

要在这里发布,我不喜欢for循环。

int[] arr = {4, 3, 6, 6, 4, 8, 1, 9, 3, 6, 7, 8, 6};

Map<Integer, Long> map = Arrays.stream(arr)
        .boxed()
        .collect(Collectors.groupingBy(
                Function.identity(), Collectors.counting()
        ));

Map.Entry<Integer, Long> max = Collections.max(
        map.entrySet(), Map.Entry.comparingByValue()
);

System.out.println(max.getKey());

首先,你按照他们的数量对它们进行分组(可能你需要的不仅仅是具有最大数量的元素?谁知道),然后你选择最大条目并从中打印出密钥。