ActiveCoder的博客

Algorithms seen

LeetCode 228. Summary Ranges

#include <vector>
#include <string>
#include <iostream>
using namespace std;

/*
  Given a sorted integer array without duplicates, return the summary of its ranges.
  For example:
  Given [0, 1, 2, 4, 5, 7], return ["0->2", "4->5", "7"]
*/
vector<string> summaryRanges(vector<int>& nums) {
  int i = 0;
  vector<string> res;
  while(i < nums.size()) {
    int tmp = nums[i];
    int j = i + 1;
    while((j < nums.size()) && ((nums[j] - nums[i]) == (j - i))) {
      j++;
    }
    if(j - i >= 2) {
      string a = to_string(tmp) + "->" + to_string(nums[j-1]);
      res.push_back(a);
    } else {
      string a  = to_string(tmp);
      res.push_back(a);
    }
    i = j - 1;
    i++;
  }
  return res;
}

int main(void) {
  vector<int> nums{0, 1, 2, 3, 4, 5, 7};
  vector<string> res = summaryRanges(nums);
  for(int i = 0; i < res.size(); ++i) {
    cout << res[i] << " ";
  }
  cout << endl;
}


Second Round: Two pointers seem easier.

// summary ranges
#include <string>
#include <vector>
#include <iostream>
using namespace std;

vector<string> summaryRanges(vector<int>& nums) {
  vector<string> res;
  if(nums.size() == 0) return {};
  int start = nums[0], end = nums[0] + 1;
  for(int i = 1; i < nums.size(); ++i) {
    if(nums[i] == end) {
      end++;
    } else {
      if(end - start < 2) {
        string tmp = to_string(start);
        res.push_back(tmp);
      } else {
        string tmp = to_string(start) + "->" + to_string(end - 1);
        res.push_back(tmp);
      }
      start = nums[i];
      end = start + 1;
    }
  }
  if(end - start >= 2) {
    string tmp = to_string(start) + "->" + to_string(end - 1);
    res.push_back(tmp);
  } else res.push_back(to_string(start));
  return res;
}

int main(void) {
  vector<int> nums{0, 1, 2};
  vector<int> nums_1{1, 3, 5, 6};
  vector<string> res = summaryRanges(nums_1);
  for(string r : res) cout << r << endl;
}


阅读更多
版权声明:欢迎转载 https://blog.csdn.net/github_34333284/article/details/51422125
个人分类: LeetCode 题解
上一篇LeetCode 18. 4Sum
下一篇LeetCode 124. Binary Tree Maximum Path Sum
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭