比较数组子序列与另一个数组

时间:2018-07-27 23:10:24

标签: javascript arrays reactjs

我遇到了一个编码挑战,要求我在1000个正整数或负整数中找到两个子序列。这两个子序列必须分别返回最大和和最小和。我已经完成了这一步,并具有三个变量:完整的数组,最小的子序列和最大的子序列。下一步是突出显示整个数组中的子序列,我不知道如何解决此步骤。抱歉,如果格式很奇怪,我是第一次发布。 enter image description here这是到目前为止的代码:

class App extends Component { constructor(props) { super(props) this.state = { arr: (Array.from({length: 1000}, () => Math.floor(Math.random() * 201) - 100)), minVals: '', maxVals: '' } } componentDidMount() { this.getSeqOfArray(this.state.arr) } getSeqOfArray = function(arr) { let min_so_far = Number.POSITIVE_INFINITY; let max_so_far = Number.NEGATIVE_INFINITY; let minLeft = 0; let maxLeft = 0; let minRight = arr.length - 1; let maxRight = arr.length - 1; let len = arr.length; for (let i = 0; i < len; i++) { for (let j = i; j < len; j++) { let minSum = 0; let maxSum = 0; for (let k = i; k <= j; k++) { minSum += arr[k]; maxSum += arr[k]; if (min_so_far > minSum) { minLeft = i; min_so_far = minSum; minRight = j; } if (max_so_far < maxSum) { maxLeft = i; max_so_far = maxSum; maxRight = j; } } } } let min = { left: minLeft, right: minRight, sequence: arr.slice(minLeft, minRight), total: min_so_far }; let max = { left: maxLeft, right: maxRight, sequence: arr.slice(maxLeft, maxRight), total: max_so_far }; this.setState({minVals: min, maxVals: max}) };

0 个答案:

没有答案