似乎无法使其正常工作我无法按要求获得中位数

问题描述

我无法得出中位数。我想从单词中得出中位数。很难从for循环中获取价值。

public class MedianWord {
    static double medianWordLength(String words) {
        String[] parts = words.split(" ");
        int[] a;
        double median = 0;

        for (int i = 0; i < parts.length; i++) {
            a = new int[parts[i].length()];
            Arrays.sort(a);
            if (a.length % 2 == 0) {
                median = ((double) a[a.length / 2] + (double) a[a.length / 2 - 1]) / 2;
            }
            else
                median = (double) a[a.length / 2];
        }
        return median;
    }
}

解决方法

每次循环迭代都会用一个新数组覆盖a数组。您需要将问题分为两部分-首先,对parts数组进行迭代,并将其转换为长度为a的数组,然后找到该数组的中位数:

static double medianWordLength(String words) {
    String[] parts = words.split(" ");
    int[] a = new int[parts.length];
    for (int i = 0; i < parts.length; i++) {
        a[i] = parts[i].length();
    }

    Arrays.sort(a);
    if (a.length % 2 == 0) {
        return ((double) a[a.length / 2] + (double) a[a.length / 2 - 1]) / 2;
    }
    else {
        return a[a.length / 2];
    }
}

旁注:
可以使用流更优雅地将单词转换为长度排序的数组:

int[] a = Arrays.stream(words.split(" ")).mapToInt(String::length).sorted().toArray();
,

应该可以:

static Integer getMedian(String sentence) {
        String[] str = sentence.split(" ");
        Integer[] strLen = new Integer[str.length];

        for (int i = 0; i < strLen.length; i++) {
            strLen[i] = str[i].length();
        }

        return strLen.length % 2 == 0?
                (strLen[strLen.length / 2] + strLen[strLen.length / 2 - 1]) / 2 : strLen[strLen.length / 2];
    }
,
public static double medianWordLength(String str) {
    int[] arr = Arrays.stream(str.split("\\s+"))
                      .mapToInt(String::length)
                      .sorted()
                      .toArray();

    int mid = arr.length / 2;
    double median = (double)arr[mid];

    return arr.length % 2 == 0 ? (median + arr[mid - 1]) / 2 : median;
}
,

首先,您要不断对数组进行排序,然后在循环中替换数组。那是你的主要问题。

但是为了简化此过程,您只需要一个数组而不需要for循环。只需根据单词的长度对单词数组进行排序。我留了一些打印声明,以便您了解发生了什么。而且,如果您在一个或多个空格上进行分割,则在输入单词字符串时不必格外小心。

To
be
or
to
be
is
not
the
that
question
----------
be is
2.0

打印

$(document).ready(function() {
  /**
  @add your hc domain here
  @for eg: var hc_url = 'https://testcompany.com'
  */
  var hc_url = 'Your_HC_URL'

  var _allarticles = [],_sorted = [],_artHtml = '',_id,_url;

  var _articles = function(article) {
    $.ajax({
      url: _url,type: 'GET',dataType: 'json',success: article
    });
  };

  // function for see all articles button in category
  $('.see-all-articles').click(function(e) {
    e.preventDefault();
    _id = $(e.target).attr('href').split('/sections/')[1].split('-')[0];

    if (typeof HelpCenter.user.locale == 'undefined') {
      HelpCenter.user.locale = window.location.pathname.replace('/','').replace('?','/').split('/')[1];
    }

    _url = hc_url + '/api/v2/help_center/' + HelpCenter.user.locale + '/sections/' + _id + '/articles.json';
    _articles(function(data) {
      _allarticles = data.articles;

      if (data.count > 30) {
        for (var i = 1; i < data.page_count; i++) {
          _url = data.next_page;
          _articles(function(data) {
            _allarticles = _allarticles.concat(data.articles);
            _arthtml = '';
            $(_allarticles).each(function(idx,itm) {
              if (itm.draft == true) {} else {
                _arthtml = _arthtml + '<li class="' + (itm.promoted == true ? 'article-promoted' : '') + '"><span data-title="Promoted article" style="' + (itm.promoted == false ? 'display:none' : '') + '">★</span><a href="' + itm.html_url + '">' + itm.title + '</a></li>';
              }
            });
            $(e.target).parent().find('ul.article-list').html(_arthtml);
            $(e.target).hide();
          })
        }
      } else {
        _arthtml = '';
        $(data.articles).each(function(idx,itm) {
          if (itm.draft == true) {} else {
            _arthtml = _arthtml + '<li class="' + (itm.promoted == true ? 'article-promoted' : '') + '"><span data-title="Promoted article" style="' + (itm.promoted == false ? 'display:none' : '') + '">★</span><a href="' + itm.html_url + '">' + itm.title + '</a></li>';
          }
        });
        $(e.target).parent().find('ul.article-list').html(_arthtml);
        $(e.target).hide();
      }

    });
  });
  // function for see all articles button in category ends here
});