几乎增加序列-Javascript

时间:2018-12-04 16:24:13

标签: javascript performance big-o

大家好,我在学习算法和数据结构时同时使用Codefights,但似乎无法解决此问题。

给出一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。

我的代码由于性能而失败,并且我有一个总体思路,为什么要考虑复制原始数组并遍历两者。但是我无法想到一种更优化的方法。

private void fetchRemoteData(final DataStatus callback) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        List<Post> listItems = new ArrayList<>();
                        List<Post> PagintationList = new ArrayList<>();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray("bgs");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject o = array.getJSONObject(i);
                                Post item = new Post(
                                        o.optString("img"),
                                        o.optString("name")
                                );
                                listItems.add(item);
                            }
                            for (int count = resetNumber; count < 10; count++) {
                                PagintationList.add(listItems.get(count));
                            }
                            resetNumber = PagintationList.size() + 1;
                            callback.onSuccess(PagintationList);
                        } catch (JSONException e) {
                            slowinternetconnection();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callback.onError(error);
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        stringRequest.setShouldCache(false);
        requestQueue.getCache().clear();
        requestQueue.add(stringRequest);
    }

5 个答案:

答案 0 :(得分:1)

这是我对问题的解决方案。我希望有人会觉得它有帮助。

function almostIncreasingSequence(sequence) {
    let flag = 0;
    for (let i = 0; i < sequence.length; i++) { 
      if (sequence[i] >= sequence[i+1]){
          flag++; 
          if(i !== 0 && sequence[i] >= sequence[i+2]){
              if(sequence[i-1] >= sequence[i+1])
                  return false;
          }
      }
  } 
  return flag < 2;
}

答案 1 :(得分:0)

正如我在评论中提到的那样,您不需要不断检查整个数组,也不需要使用多个循环。

可以将问题分解为较小的问题。对于列表中的每个元素...

  • 当前元素是否大于最后一个元素(递增)?
    • 是的...
      • 好!我们不需要做任何事情。
    • 不...
      • 这已经发生了吗?如果是这样,并没有增加。
      • 如果我们删除上一个项目,周围的项目是否固定?
      • 不?如果我们改为删除 current 项怎么办?
      • 还是不?那就意味着我们不能一move而就。 并没有增加。

代码看起来像这样:

function almostIncreasingSequence(sequence) {
  let invalidItemsCount = 0;
  
  for (let i = 1; i < sequence.length; i++) {
    if (sequence[i] <= sequence[i-1]) {
      invalidItemsCount++;
      if (invalidItemsCount > 1) return false;
      if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
    }
  }
  
  return true;
}

var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];

console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));

评论版本:

function almostIncreasingSequence(sequence) {
  //Keep track of how many replacements we've had to make
  let invalidItemsCount = 0;
  
  //Start our loop at 1 so that [i-1] doesn't refer to index "-1"
  for (let i = 1; i < sequence.length; i++) {
  
    //If this item is not increasing, we'll need to address it
    if (sequence[i] <= sequence[i-1]) {
    
      //Increment our invalidItemsCount
      invalidItemsCount++;               
      
      //If this is our second invalidItem, then it's not almost increasing.
      if (invalidItemsCount > 1) return false;  
      
      //If removing the previous element doesn't help, and removing the current item doesn't help,
      //then we can't solve this in one move. It's not almost increasing.
      if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
      
    }
  }
  
  //We've made it through the entire loop without fail. This is almost increasing.
  return true;
}

var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];

console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));

答案 2 :(得分:0)

所以我正在用Python做CodeFights。而且我一直受这份任务困扰。我发现关于StackOverflow的每个答案都包含很多长期条件。因此,我想,这对于人们了解我的解决方案很有用。我敢肯定,可以用更好的样式来重写它,但是这种方法更具直觉

def almostIncreasingSequence(sequence):
    def isIncreasingSequence(sequence, skip = None):
        to_use = list.copy(sequence)
        if skip != None:
            del to_use[skip]
        for i in range(1, len(to_use)):
            if to_use[i] <= to_use[i-1]:
                return False
        return True

    for i in range(1, len(sequence)):
        if(sequence[i - 1] >= sequence[i]):
            return isIncreasingSequence(sequence, i-1) or  isIncreasingSequence(sequence, i)
    return True

答案 3 :(得分:0)

我在TypeScript中提出了这个解决方案,我在这里提出了一些反馈。 之所以有效,是因为布尔值最初是未定义的。

function almostIncreasingSequence(sequence: number[]): boolean {

let joker : boolean;
console.log(joker);
for (let index = 1; index < sequence.length; index++) {
    const element = sequence[index];
    if (sequence[index] <= sequence[index-1]) {
        if (!joker) {
            joker = true;     
        } else {
            return false;
        }
    } 
}
return true;
}

答案 4 :(得分:-1)

package main

import "fmt"

func main() {
    fmt.Println(almostIncreasingSequence([]int{10, 1, 2, 3, 4, 5}))
    fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 2, 3, 6}))
    fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 99, 5, 6}))
    fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 5, 6, 5}))
    fmt.Println(almostIncreasingSequence([]int{1, 5, 3, 4, 5, 6, 5}))
}

func almostIncreasingSequence(sequence []int) bool {
    count := 0
    for i := 1; i <= len(sequence)-1; i++ {
        if sequence[i] <= sequence[i-1] {
            count++
            if count > 1 {
                return false
            }

            if i <= 1 || i == len(sequence)-1 {
                continue
            }

            if sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1] {
                return false
            }
            continue
        }
    }
    return true
}

相关问题